Снятие колес работает, покраска тоже более менее. Физика просто говно щяс

This commit is contained in:
bybohka committed 2026-10-20 17:54:31 +03:00
1 parent d4c84b10df
commit 2ce853999d
67 files changed
+155997 -2074

No files matched your search

+1 -54
View File
@@ -81,58 +81,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/System.Collections.Generic.List(AIGD.PackageData)"
}
},
"$defs": {
"AIGD.PackageData": {
"type": "object",
"properties": {
"Name": {
"type": "string",
"description": "The official Unity name of the package used as the package ID."
},
"DisplayName": {
"type": "string",
"description": "The display name of the package."
},
"Version": {
"type": "string",
"description": "The version of the package."
},
"Description": {
"type": "string",
"description": "A brief description of the package."
},
"Source": {
"type": "string",
"description": "The source of the package (Registry, Embedded, Local, Git, etc.)."
},
"Category": {
"type": "string",
"description": "The category of the package."
}
},
"description": "Package information returned from package list operation."
},
"System.Collections.Generic.List(AIGD.PackageData)": {
"type": "array",
"items": {
"$ref": "#/$defs/AIGD.PackageData",
"description": "Package information returned from package list operation."
}
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+1 -67
View File
@@ -79,71 +79,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/System.Collections.Generic.List(AIGD.PackageSearchResult)"
}
},
"$defs": {
"AIGD.PackageSearchResult": {
"type": "object",
"properties": {
"Name": {
"type": "string",
"description": "The official Unity name of the package used as the package ID."
},
"DisplayName": {
"type": "string",
"description": "The display name of the package."
},
"LatestVersion": {
"type": "string",
"description": "The latest version available in the registry."
},
"Description": {
"type": "string",
"description": "A brief description of the package."
},
"IsInstalled": {
"type": "boolean",
"description": "Whether this package is already installed in the project."
},
"InstalledVersion": {
"type": "string",
"description": "The currently installed version (if installed)."
},
"AvailableVersions": {
"$ref": "#/$defs/System.Collections.Generic.List(System.String)",
"description": "Available versions of this package (up to 5 most recent)."
}
},
"required": [
"IsInstalled"
],
"description": "Package search result with available versions."
},
"System.Collections.Generic.List(System.String)": {
"type": "array",
"items": {
"type": "string"
}
},
"System.Collections.Generic.List(AIGD.PackageSearchResult)": {
"type": "array",
"items": {
"$ref": "#/$defs/AIGD.PackageSearchResult",
"description": "Package search result with available versions."
}
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+2 -44
View File
@@ -50,7 +50,7 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `cameraRef` | `any` | No | Reference to the camera GameObject. If not specified, uses the Main Camera. |
| `cameraRef` | `string` | No | Reference to the camera GameObject. If not specified, uses the Main Camera. RQL: GameObjectRef |
| `width` | `integer` | No | Width of the screenshot in pixels. |
| `height` | `integer` | No | Height of the screenshot in pixels. |
@@ -61,7 +61,7 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "object",
"properties": {
"cameraRef": {
"$ref": "#/$defs/AIGD.GameObjectRef"
"type": "string"
},
"width": {
"type": "integer"
@@ -69,48 +69,6 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"height": {
"type": "integer"
}
},
"$defs": {
"UnityEngine.EntityId": {
"type": "string",
"pattern": "^[0-9]+$"
},
"System.Type": {
"type": "string"
},
"AIGD.GameObjectRef": {
"type": "object",
"properties": {
"instanceID": {
"$ref": "#/$defs/UnityEngine.EntityId",
"description": "instanceID of the UnityEngine.Object. If it is '0' and 'path', 'name', 'assetPath' and 'assetGuid' is not provided, empty or null, then it will be used as 'null'. Priority: 1 (Recommended)"
},
"path": {
"type": "string",
"description": "Path of a GameObject in the hierarchy Sample 'character/hand/finger/particle'. Priority: 2."
},
"name": {
"type": "string",
"description": "Name of a GameObject in hierarchy. Priority: 3."
},
"assetType": {
"$ref": "#/$defs/System.Type",
"description": "Type of the asset."
},
"assetPath": {
"type": "string",
"description": "Path to the asset within the project. Starts with 'Assets/'"
},
"assetGuid": {
"type": "string",
"description": "Unique identifier for the asset."
}
},
"required": [
"instanceID"
],
"description": "Find GameObject in opened Prefab or in the active Scene."
}
}
}
```
+40 -97
View File
@@ -32,17 +32,17 @@ Isolation temporarily activates inactive child GameObjects so their renderers pa
```bash
unity-mcp-cli run-tool screenshot-isolated --input '{
"gameObjectRef": "string_value",
"includeChildren": "string_value",
"isolated": "string_value",
"includeChildren": false,
"isolated": false,
"backgroundMode": "string_value",
"backgroundColor": "string_value",
"cameraView": "string_value",
"fieldOfView": "string_value",
"nearClipPlane": "string_value",
"farClipPlane": "string_value",
"padding": "string_value",
"fieldOfView": 0,
"nearClipPlane": 0,
"farClipPlane": 0,
"padding": 0,
"lights": "string_value",
"resolution": "string_value"
"resolution": 0
}'
```
@@ -68,18 +68,18 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `gameObjectRef` | `any` | Yes | Reference to the target GameObject (by instanceId, path, or name). |
| `includeChildren` | `any` | No | Include child GameObjects in the render. Default: true. |
| `isolated` | `any` | No | When true, renders only the target object using layer-based culling. When false, renders the full scene from the computed camera position. Default: true. |
| `backgroundMode` | `any` | No | Background mode. Default: SolidColor. |
| `gameObjectRef` | `string` | Yes | Reference to the target GameObject (by instanceId, path, or name). RQL: GameObjectRef |
| `includeChildren` | `boolean` | No | Include child GameObjects in the render. Default: true. |
| `isolated` | `boolean` | No | When true, renders only the target object using layer-based culling. When false, renders the full scene from the computed camera position. Default: true. |
| `backgroundMode` | `string` | No | Background mode. Default: SolidColor. |
| `backgroundColor` | `string` | No | Hex background color (e.g. '#404040'). Only used when backgroundMode is SolidColor. |
| `cameraView` | `any` | No | Camera angle relative to the target object's bounding box. Default: Front. |
| `fieldOfView` | `any` | No | Camera vertical field of view in degrees. Default: 60. |
| `nearClipPlane` | `any` | No | Camera near clip plane distance. Default: 0.01. |
| `farClipPlane` | `any` | No | Camera far clip plane distance. Default: 1000. |
| `padding` | `any` | No | Framing multiplier around the object. 1.0 = tight fit, 1.5 = 50% extra space. Default: 1.2. |
| `cameraView` | `string` | No | Camera angle relative to the target object's bounding box. Default: Front. |
| `fieldOfView` | `number` | No | Camera vertical field of view in degrees. Default: 60. |
| `nearClipPlane` | `number` | No | Camera near clip plane distance. Default: 0.01. |
| `farClipPlane` | `number` | No | Camera far clip plane distance. Default: 1000. |
| `padding` | `number` | No | Framing multiplier around the object. 1.0 = tight fit, 1.5 = 50% extra space. Default: 1.2. |
| `lights` | `string` | No | JSON array of light configurations. Each object defines type, color, intensity, rotation, position, range, spotAngle, shadows, etc. When null, a default white directional light at rotation (50,-30,0) is used. Example: [{"type":"Directional","color":"#FFF4E5","intensity":1.2,"rotation":[45,-45,0]}] |
| `resolution` | `any` | No | Output image resolution in pixels (width = height). Default: 512. |
| `resolution` | `integer` | No | Output image resolution in pixels (width = height). Default: 512. |
### Input JSON Schema
@@ -88,87 +88,15 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "object",
"properties": {
"gameObjectRef": {
"$ref": "#/$defs/AIGD.GameObjectRef"
"type": "string"
},
"includeChildren": {
"$ref": "#/$defs/System.Boolean"
},
"isolated": {
"$ref": "#/$defs/System.Boolean"
},
"backgroundMode": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.Tool_Screenshot-BackgroundMode"
},
"backgroundColor": {
"type": "string"
},
"cameraView": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.Tool_Screenshot-CameraView"
},
"fieldOfView": {
"$ref": "#/$defs/System.Single"
},
"nearClipPlane": {
"$ref": "#/$defs/System.Single"
},
"farClipPlane": {
"$ref": "#/$defs/System.Single"
},
"padding": {
"$ref": "#/$defs/System.Single"
},
"lights": {
"type": "string"
},
"resolution": {
"$ref": "#/$defs/System.Int32"
}
},
"$defs": {
"UnityEngine.EntityId": {
"type": "string",
"pattern": "^[0-9]+$"
},
"System.Type": {
"type": "string"
},
"AIGD.GameObjectRef": {
"type": "object",
"properties": {
"instanceID": {
"$ref": "#/$defs/UnityEngine.EntityId",
"description": "instanceID of the UnityEngine.Object. If it is '0' and 'path', 'name', 'assetPath' and 'assetGuid' is not provided, empty or null, then it will be used as 'null'. Priority: 1 (Recommended)"
},
"path": {
"type": "string",
"description": "Path of a GameObject in the hierarchy Sample 'character/hand/finger/particle'. Priority: 2."
},
"name": {
"type": "string",
"description": "Name of a GameObject in hierarchy. Priority: 3."
},
"assetType": {
"$ref": "#/$defs/System.Type",
"description": "Type of the asset."
},
"assetPath": {
"type": "string",
"description": "Path to the asset within the project. Starts with 'Assets/'"
},
"assetGuid": {
"type": "string",
"description": "Unique identifier for the asset."
}
},
"required": [
"instanceID"
],
"description": "Find GameObject in opened Prefab or in the active Scene."
},
"System.Boolean": {
"type": "boolean"
},
"com.IvanMurzak.Unity.MCP.Editor.API.Tool_Screenshot-BackgroundMode": {
"isolated": {
"type": "boolean"
},
"backgroundMode": {
"type": "string",
"enum": [
"SolidColor",
@@ -176,7 +104,10 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"Transparent"
]
},
"com.IvanMurzak.Unity.MCP.Editor.API.Tool_Screenshot-CameraView": {
"backgroundColor": {
"type": "string"
},
"cameraView": {
"type": "string",
"enum": [
"Front",
@@ -188,10 +119,22 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"Composite"
]
},
"System.Single": {
"fieldOfView": {
"type": "number"
},
"System.Int32": {
"nearClipPlane": {
"type": "number"
},
"farClipPlane": {
"type": "number"
},
"padding": {
"type": "number"
},
"lights": {
"type": "string"
},
"resolution": {
"type": "integer"
}
},
+2 -7
View File
@@ -22,7 +22,7 @@ Validates the array (non-empty, every entry ends with `.cs`, every entry exists)
```bash
unity-mcp-cli run-tool script-delete --input '{
"files": "string_value"
"files": []
}'
```
@@ -48,7 +48,7 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `files` | `any` | Yes | File paths to the files. Sample: "Assets/Scripts/MyScript.cs". |
| `files` | `array` | Yes | File paths to the files. Sample: "Assets/Scripts/MyScript.cs". |
### Input JSON Schema
@@ -57,11 +57,6 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "object",
"properties": {
"files": {
"$ref": "#/$defs/System.String-1"
}
},
"$defs": {
"System.String-1": {
"type": "array",
"items": {
"type": "string"
+4 -106
View File
@@ -59,8 +59,8 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| `csharpCode` | `string` | Yes | C# code to compile and execute. In full code mode (default, isMethodBody=false): must define a complete class with a static method. Example: 'using UnityEngine; public class Script { public static void Main() { Debug.Log("Hello"); } }'. Do NOT use top-level statements. In body-only mode (isMethodBody=true): provide only the method body statements. The tool auto-generates usings, class, and method header. Example body: 'go.SetActive(false);'. Custom helper classes can still be defined inline in the body-only string after the main logic, but for complex additional class definitions use full code mode instead. |
| `className` | `string` | No | The name of the class containing the method to execute. In body-only mode this becomes the generated class name. |
| `methodName` | `string` | No | The name of the method to execute. Must be a static method. In body-only mode this becomes the generated method name. |
| `parameters` | `any` | No | Serialized parameters to pass to the method. Each entry must specify 'name' and 'typeName'. Supported parameter types include primitives, strings, and Unity object references: - 'UnityEngine.GameObject': resolves an actual GameObject from value '{"instanceID": N}', '{"name": "..."}', or '{"path": "..."}'. - 'UnityEngine.Component' (or any component subtype): resolves from '{"instanceID": N}'. - 'AIGD.GameObjectRef': passes a GameObjectRef POCO directly; the method body calls goRef.FindGameObject() to resolve it. - 'AIGD.ComponentRef': passes a ComponentRef POCO. - 'AIGD.ObjectRef': passes a base ObjectRef POCO. If the method does not require parameters, leave this empty. |
| `isMethodBody` | `boolean` | No | When true, 'csharpCode' is treated as just the method body. The tool auto-generates standard using directives (System, UnityEngine, AIGD, com.IvanMurzak.Unity.MCP.Runtime.Extensions, UnityEditor), the class definition, and the method signature (void return type). Parameters from the 'parameters' list are automatically added to the method signature using their typeName and name. When false (default), 'csharpCode' must be a complete C# compilation unit with class and method definitions. |
| `parameters` | `string` | No | Values for the method's parameters by name, e.g. {go: ref("GameObject#12"), n: 6}. Leave empty if the method takes none. RQL: SerializedMemberList |
| `isMethodBody` | `boolean` | No | When true, 'csharpCode' is treated as just the method body. The tool auto-generates standard using directives (System, UnityEngine, AIGD, com.IvanMurzak.Unity.MCP.Runtime.Extensions, UnityEditor), the class definition, and the method signature (returns object when the body returns a value, void otherwise). Parameters from the 'parameters' list are automatically added to the method signature using their typeName and name. When false (default), 'csharpCode' must be a complete C# compilation unit with class and method definitions. |
### Input JSON Schema
@@ -78,56 +78,12 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "string"
},
"parameters": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMemberList"
"type": "string"
},
"isMethodBody": {
"type": "boolean"
}
},
"$defs": {
"com.IvanMurzak.ReflectorNet.Model.SerializedMemberList": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember"
}
},
"com.IvanMurzak.ReflectorNet.Model.SerializedMember": {
"type": "object",
"properties": {
"typeName": {
"type": "string",
"description": "Full type name. Eg: 'System.String', 'System.Int32', 'UnityEngine.Vector3', etc."
},
"name": {
"type": "string",
"description": "Object name."
},
"value": {
"description": "Value of the object, serialized as a non stringified JSON element. Can be null if the value is not set. Can be default value if the value is an empty object or array json."
},
"fields": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember",
"description": "Nested field value."
},
"description": "Fields of the object, serialized as a list of 'SerializedMember'."
},
"props": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember",
"description": "Nested property value."
},
"description": "Properties of the object, serialized as a list of 'SerializedMember'."
}
},
"required": [
"typeName"
],
"additionalProperties": false
}
},
"required": [
"csharpCode"
]
@@ -136,63 +92,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember"
}
},
"$defs": {
"com.IvanMurzak.ReflectorNet.Model.SerializedMemberList": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember"
}
},
"com.IvanMurzak.ReflectorNet.Model.SerializedMember": {
"type": "object",
"properties": {
"typeName": {
"type": "string",
"description": "Full type name. Eg: 'System.String', 'System.Int32', 'UnityEngine.Vector3', etc."
},
"name": {
"type": "string",
"description": "Object name."
},
"value": {
"description": "Value of the object, serialized as a non stringified JSON element. Can be null if the value is not set. Can be default value if the value is an empty object or array json."
},
"fields": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember",
"description": "Nested field value."
},
"description": "Fields of the object, serialized as a list of 'SerializedMember'."
},
"props": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.SerializedMember",
"description": "Nested property value."
},
"description": "Properties of the object, serialized as a list of 'SerializedMember'."
}
},
"required": [
"typeName"
],
"additionalProperties": false
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+1 -15
View File
@@ -79,19 +79,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"type": "string"
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+13 -143
View File
@@ -13,6 +13,8 @@ Execute Unity tests and return detailed results. Supports filtering by test mode
- `testMode` (default `EditMode`) — `EditMode` or `PlayMode`. EditMode is faster; prefer it during iteration.
- `testAssembly` / `testNamespace` / `testClass` / `testMethod` — optional, layered filters. Namespace and class filters become regex `groupNames` so the validation count and Unity's execution stay in sync. `testMethod` must be fully qualified (`Namespace.FixtureName.TestName`).
- `query` — RQL over the `tests` source instead of the four filters: any selection, run as ONE Test Runner run, e.g. `tests | where fixture == "PlayerTests" or categories contains "Smoke"`. One mode per run; the mode comes from the selected tests. Explore first with rql-query: `tests | where fullName contains "Spline" | select fullName mode`.
- `result` — RQL stages applied to the results (source `testResults`: name status durationMs message stackTrace), e.g. `where status == "Failed" | select name message`; the answer is then a summary line plus compact RQL text.
## Response toggles
@@ -36,6 +38,8 @@ unity-mcp-cli run-tool tests-run --input '{
"testNamespace": "string_value",
"testClass": "string_value",
"testMethod": "string_value",
"query": "string_value",
"result": "string_value",
"includePassingTests": false,
"includeMessages": false,
"includeStacktrace": false,
@@ -72,6 +76,8 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| `testNamespace` | `string` | No | Specific test namespace to run (optional). Example: 'MyTestNamespace' |
| `testClass` | `string` | No | Specific test class name to run (optional). Example: 'MyTestClass' |
| `testMethod` | `string` | No | Specific fully qualified test method to run (optional). Example: 'MyTestNamespace.FixtureName.TestName' |
| `query` | `string` | No | RQL over the 'tests' source selecting the tests (instead of the filters above), run as one run. Example: tests | where fullName contains "Player" and mode == "EditMode" |
| `result` | `string` | No | RQL stages applied to the results (source 'testResults': name status durationMs message stackTrace); the answer is a summary line plus compact text. Example: where status == "Failed" | select name message |
| `includePassingTests` | `boolean` | No | Include details for all tests, both passing and failing (default: false). If you just need details for failing tests, set to false. |
| `includeMessages` | `boolean` | No | Include test result messages in the test results (default: true). If you just need pass/fail status, set to false. |
| `includeStacktrace` | `boolean` | No | Include stack traces in the test results (default: false). |
@@ -104,6 +110,12 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"testMethod": {
"type": "string"
},
"query": {
"type": "string"
},
"result": {
"type": "string"
},
"includePassingTests": {
"type": "boolean"
},
@@ -135,147 +147,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestRunResponse"
}
},
"$defs": {
"com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestSummaryData": {
"type": "object",
"properties": {
"Status": {
"type": "string",
"enum": [
"Unknown",
"Passed",
"Failed"
]
},
"TotalTests": {
"type": "integer"
},
"PassedTests": {
"type": "integer"
},
"FailedTests": {
"type": "integer"
},
"SkippedTests": {
"type": "integer"
},
"Duration": {
"type": "string"
}
},
"required": [
"Status",
"TotalTests",
"PassedTests",
"FailedTests",
"SkippedTests",
"Duration"
]
},
"System.Collections.Generic.List(com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestResultData)": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestResultData"
}
},
"com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestResultData": {
"type": "object",
"properties": {
"Name": {
"type": "string"
},
"Status": {
"type": "string",
"enum": [
"Passed",
"Failed",
"Skipped"
]
},
"Duration": {
"type": "string"
},
"Message": {
"type": "string"
},
"StackTrace": {
"type": "string"
}
},
"required": [
"Status",
"Duration"
]
},
"System.Collections.Generic.List(com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestLogEntry)": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestLogEntry"
}
},
"com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestLogEntry": {
"type": "object",
"properties": {
"Condition": {
"type": "string"
},
"StackTrace": {
"type": "string"
},
"Type": {
"type": "string",
"enum": [
"Error",
"Assert",
"Warning",
"Log",
"Exception"
]
},
"Timestamp": {
"type": "string",
"format": "date-time"
},
"LogLevel": {
"type": "integer"
}
},
"required": [
"Type",
"Timestamp"
]
},
"com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestRunResponse": {
"type": "object",
"properties": {
"Summary": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestSummaryData",
"description": "Summary of the test run including total, passed, failed, and skipped counts."
},
"Results": {
"$ref": "#/$defs/System.Collections.Generic.List(com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestResultData)",
"description": "List of individual test results with details about each test."
},
"Logs": {
"$ref": "#/$defs/System.Collections.Generic.List(com.IvanMurzak.Unity.MCP.Editor.API.TestRunner.TestLogEntry)",
"description": "Log entries captured during test execution."
}
}
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+5 -100
View File
@@ -23,7 +23,7 @@ Each entry is resolved against the tool manager's exact-name and case-insensitiv
```bash
unity-mcp-cli run-tool tool-set-enabled-state --input '{
"tools": "string_value",
"includeLogs": "string_value"
"includeLogs": false
}'
```
@@ -49,8 +49,8 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `tools` | `any` | Yes | Array of tools with their desired enabled state. |
| `includeLogs` | `any` | No | Include operation logs in the result. Default: false |
| `tools` | `string` | Yes | Array of tools with their desired enabled state. RQL: [ToolToggleInput] |
| `includeLogs` | `boolean` | No | Include operation logs in the result. Default: false |
### Input JSON Schema
@@ -59,36 +59,9 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "object",
"properties": {
"tools": {
"$ref": "#/$defs/AIGD.ToolToggleInput-1"
"type": "string"
},
"includeLogs": {
"$ref": "#/$defs/System.Boolean"
}
},
"$defs": {
"AIGD.ToolToggleInput": {
"type": "object",
"properties": {
"Name": {
"type": "string",
"description": "Name of the MCP tool to enable or disable."
},
"Enabled": {
"type": "boolean",
"description": "Whether the tool should be enabled (true) or disabled (false)."
}
},
"required": [
"Enabled"
]
},
"AIGD.ToolToggleInput-1": {
"type": "array",
"items": {
"$ref": "#/$defs/AIGD.ToolToggleInput"
}
},
"System.Boolean": {
"type": "boolean"
}
},
@@ -100,73 +73,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/AIGD.ToolToggleResult"
}
},
"$defs": {
"com.IvanMurzak.ReflectorNet.Model.Logs": {
"type": "array",
"items": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.LogEntry"
}
},
"com.IvanMurzak.ReflectorNet.Model.LogEntry": {
"type": "object",
"properties": {
"Depth": {
"type": "integer"
},
"Message": {
"type": "string"
},
"Type": {
"type": "string",
"enum": [
"Trace",
"Debug",
"Info",
"Success",
"Warning",
"Error",
"Critical"
]
}
},
"required": [
"Depth",
"Type"
]
},
"System.Collections.Generic.Dictionary(System.String,System.Boolean)": {
"type": "object",
"additionalProperties": {
"type": "boolean"
}
},
"AIGD.ToolToggleResult": {
"type": "object",
"properties": {
"Logs": {
"$ref": "#/$defs/com.IvanMurzak.ReflectorNet.Model.Logs",
"description": "Optional operation logs. Only included when 'includeLogs' is true."
},
"Success": {
"$ref": "#/$defs/System.Collections.Generic.Dictionary(System.String,System.Boolean)",
"description": "Result of each tool operation. Key: original input name as provided by the caller (case preserved as-is). Value: true if the enable/disable operation completed successfully, false if the name was unknown, ambiguous, or empty."
}
}
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+1 -1
View File
@@ -179,7 +179,7 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `path` | `string` | Yes | Path for the C# (.cs) file to be created. Sample: "Assets/Skills/MySkill.cs".
CRITICAL — Assembly Definition placement: If the project uses Assembly Definition files (.asmdef), you MUST place the script inside a folder that belongs to an assembly definition which already references all required dependencies (e.g. com.IvanMurzak.McpPlugin, UnityEditor, UnityEngine). Placing the file in the wrong assembly will cause compile errors due to missing type references. Before choosing a path, inspect existing .asmdef files with the assets-find tool to identify the correct assembly folder. |
CRITICAL — Assembly Definition placement: If the project uses Assembly Definition files (.asmdef), you MUST place the script inside a folder that belongs to an assembly definition which already references all required dependencies (e.g. com.IvanMurzak.McpPlugin, UnityEditor, UnityEngine). Placing the file in the wrong assembly will cause compile errors due to missing type references. Before choosing a path, inspect existing .asmdef files with the rql-query tool (e.g. unity.assets("t:AssemblyDefinitionAsset")) to identify the correct assembly folder. |
| `code` | `string` | Yes | C# code for the skill tool. |
### Input JSON Schema
+6 -77
View File
@@ -24,7 +24,7 @@ Iterates `UnityMcpPluginEditor.Instance.Tools.GetAllTools()`, evaluates the filt
```bash
unity-mcp-cli run-tool unity-tool-list --input '{
"regexSearch": "string_value",
"includeDescription": "string_value",
"includeDescription": false,
"includeInputs": "string_value"
}'
```
@@ -52,8 +52,8 @@ Read the /unity-initial-setup skill for detailed installation instructions.
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `regexSearch` | `string` | No | Regex pattern to filter tools. Matches against tool name, description, and argument names and descriptions. |
| `includeDescription` | `any` | No | Include tool descriptions in the result. Default: false |
| `includeInputs` | `any` | No | Include input arguments in the result. Default: None |
| `includeDescription` | `boolean` | No | Include tool descriptions in the result. Default: false |
| `includeInputs` | `string` | No | Include input arguments in the result. Default: None |
### Input JSON Schema
@@ -65,24 +65,15 @@ Read the /unity-initial-setup skill for detailed installation instructions.
"type": "string"
},
"includeDescription": {
"$ref": "#/$defs/System.Boolean"
},
"includeInputs": {
"$ref": "#/$defs/com.IvanMurzak.Unity.MCP.Editor.API.Tool_Tool-InputRequest"
}
},
"$defs": {
"System.Boolean": {
"type": "boolean"
},
"com.IvanMurzak.Unity.MCP.Editor.API.Tool_Tool-InputRequest": {
"includeInputs": {
"type": "string",
"enum": [
"None",
"Inputs",
"InputsWithDescription"
],
"description": "Specifies what to include for tool input arguments."
]
}
}
}
@@ -90,67 +81,5 @@ Read the /unity-initial-setup skill for detailed installation instructions.
## Output
### Output JSON Schema
```json
{
"type": "object",
"properties": {
"result": {
"$ref": "#/$defs/AIGD.ToolInfoData-1"
}
},
"$defs": {
"AIGD.ToolInfoData": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Tool name."
},
"description": {
"type": "string",
"description": "Tool description."
},
"inputs": {
"$ref": "#/$defs/AIGD.ToolInputData-1",
"description": "Tool input arguments."
}
},
"description": "MCP tool information."
},
"AIGD.ToolInputData-1": {
"type": "array",
"items": {
"$ref": "#/$defs/AIGD.ToolInputData",
"description": "MCP tool input argument."
}
},
"AIGD.ToolInputData": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Argument name."
},
"description": {
"type": "string",
"description": "Argument description."
}
},
"description": "MCP tool input argument."
},
"AIGD.ToolInfoData-1": {
"type": "array",
"items": {
"$ref": "#/$defs/AIGD.ToolInfoData",
"description": "MCP tool information."
}
}
},
"required": [
"result"
]
}
```
This tool does not return structured output.
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3b30c714461bb8c44a622a4003d479f1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 0e5b156a5caf91b4c86ad02a2888f685
folderAsset: yes
timeCreated: 1490210548
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,138 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &-841801551188454941
MonoBehaviour:
m_ObjectHideFlags: 11
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 10
--- !u!21 &2100000
Material:
serializedVersion: 8
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Wrench_Combination_Metal
m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_Parent: {fileID: 0}
m_ModifiedSerializedProperties: 0
m_ValidKeywords: []
m_InvalidKeywords: []
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap:
RenderType: Opaque
disabledShaderPasses:
- MOTIONVECTORS
m_LockedProperties:
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BaseMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_Lightmaps:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_LightmapsInd:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_ShadowMasks:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Ints: []
m_Floats:
- _AddPrecomputedVelocity: 0
- _AlphaClip: 0
- _AlphaToMask: 0
- _Blend: 0
- _BlendModePreserveSpecular: 1
- _BumpScale: 1
- _ClearCoatMask: 0
- _ClearCoatSmoothness: 0
- _Cull: 2
- _Cutoff: 0.5
- _DetailAlbedoMapScale: 1
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlendAlpha: 0
- _EnvironmentReflections: 1
- _GlossMapScale: 1
- _Glossiness: 0.30996522
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _QueueOffset: 0
- _ReceiveShadows: 1
- _Smoothness: 0.30996522
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlendAlpha: 1
- _Surface: 0
- _UVSec: 0
- _WorkflowMode: 1
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 0.72092414, g: 0.72092414, b: 0.72092414, a: 1}
- _Color: {r: 0.72092414, g: 0.72092414, b: 0.72092414, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 0}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
m_BuildTextureStacks: []
m_AllowLocking: 1
@@ -0,0 +1,15 @@
fileFormatVersion: 2
guid: fe711f220fb45f041a89e997d1a81142
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 86242
packageName: Workplace Tools
packageVersion: 1.2
assetPath: Assets/Workplace Tools/Materials/Wrench_Combination_Metal.mat
uploadId: 729009
+9
View File
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b752eb5dede1fb343ae4c6e7973984bb
folderAsset: yes
timeCreated: 1491901767
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.
@@ -0,0 +1,174 @@
fileFormatVersion: 2
guid: 004a97f809c2c7c40b973eabe880a410
ModelImporter:
serializedVersion: 22200
internalIDToNameTable:
- first:
1: 100000
second: Body
- first:
1: 100002
second: //RootNode
- first:
1: 100004
second: Top_Front
- first:
1: 100006
second: Trigger_Main
- first:
4: 400000
second: Body
- first:
4: 400002
second: //RootNode
- first:
4: 400004
second: Top_Front
- first:
4: 400006
second: Trigger_Main
- first:
23: 2300000
second: Body
- first:
23: 2300002
second: Top_Front
- first:
23: 2300004
second: Trigger_Main
- first:
33: 3300000
second: Body
- first:
33: 3300002
second: Top_Front
- first:
33: 3300004
second: Trigger_Main
- first:
43: 4300000
second: Trigger_Main
- first:
43: 4300002
second: Top_Front
- first:
43: 4300004
second: Body
- first:
64: 6400000
second: Body
- first:
64: 6400002
second: Top_Front
- first:
64: 6400004
second: Trigger_Main
externalObjects: {}
materials:
materialImportMode: 2
materialName: 0
materialSearch: 1
materialLocation: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
removeConstantScaleCurves: 0
motionNodeName:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations: []
isReadable: 1
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 0
addColliders: 1
useSRGBMaterialColor: 1
sortHierarchyByName: 1
importPhysicalCameras: 0
importVisibility: 0
importBlendShapes: 1
importCameras: 0
importLights: 0
nodeNameCollisionStrategy: 0
fileIdsGeneration: 1
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
keepQuads: 0
weldVertices: 1
bakeAxisConversion: 0
preserveHierarchy: 0
skinWeightsMode: 0
maxBonesPerVertex: 4
minBoneWeight: 0.001
optimizeBones: 1
meshOptimizationFlags: -1
indexFormat: 1
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVMarginMethod: 0
secondaryUVMinLightmapResolution: 40
secondaryUVMinObjectScale: 1
secondaryUVPackMargin: 4
useFileScale: 1
strictVertexDataChecks: 0
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
normalCalculationMode: 0
legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 1
blendShapeNormalImportMode: 1
normalSmoothingSource: 0
referencedClips: []
importAnimation: 1
humanDescription:
serializedVersion: 3
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
globalScale: 1
rootMotionBoneName:
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 0
lastHumanDescriptionAvatarSource: {instanceID: 0}
autoGenerateAvatarMappingIfUnspecified: 1
animationType: 0
humanoidOversampling: 1
avatarSetup: 0
addHumanoidExtraRootOnlyWhenUsingAvatar: 0
importBlendShapeDeformPercent: 0
remapMaterialsIfMaterialImportModeIsNone: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 86242
packageName: Workplace Tools
packageVersion: 1.2
assetPath: Assets/Workplace Tools/Mesh/Drill.fbx
uploadId: 729009
Binary file not shown.
@@ -0,0 +1,137 @@
fileFormatVersion: 2
guid: 36b5cba1111e25849b7ad46d9ad3f85e
ModelImporter:
serializedVersion: 22200
internalIDToNameTable:
- first:
1: 100000
second: //RootNode
- first:
4: 400000
second: //RootNode
- first:
23: 2300000
second: //RootNode
- first:
33: 3300000
second: //RootNode
- first:
43: 4300000
second: Wrench_Combination
- first:
64: 6400000
second: //RootNode
externalObjects:
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: Wrench_Combination_Metal
second: {fileID: 2100000, guid: fe711f220fb45f041a89e997d1a81142, type: 2}
materials:
materialImportMode: 2
materialName: 0
materialSearch: 1
materialLocation: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
removeConstantScaleCurves: 0
motionNodeName:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations: []
isReadable: 1
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 0
addColliders: 1
useSRGBMaterialColor: 1
sortHierarchyByName: 1
importPhysicalCameras: 0
importVisibility: 0
importBlendShapes: 1
importCameras: 0
importLights: 0
nodeNameCollisionStrategy: 0
fileIdsGeneration: 1
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
keepQuads: 0
weldVertices: 1
bakeAxisConversion: 0
preserveHierarchy: 0
skinWeightsMode: 0
maxBonesPerVertex: 4
minBoneWeight: 0.001
optimizeBones: 1
meshOptimizationFlags: -1
indexFormat: 1
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVMarginMethod: 0
secondaryUVMinLightmapResolution: 40
secondaryUVMinObjectScale: 1
secondaryUVPackMargin: 4
useFileScale: 1
strictVertexDataChecks: 0
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
normalCalculationMode: 0
legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 1
blendShapeNormalImportMode: 1
normalSmoothingSource: 0
referencedClips: []
importAnimation: 1
humanDescription:
serializedVersion: 3
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
globalScale: 1
rootMotionBoneName:
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 0
lastHumanDescriptionAvatarSource: {instanceID: 0}
autoGenerateAvatarMappingIfUnspecified: 1
animationType: 0
humanoidOversampling: 1
avatarSetup: 0
addHumanoidExtraRootOnlyWhenUsingAvatar: 0
importBlendShapeDeformPercent: 0
remapMaterialsIfMaterialImportModeIsNone: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 86242
packageName: Workplace Tools
packageVersion: 1.2
assetPath: Assets/Workplace Tools/Mesh/Wrench_Combination.fbx
uploadId: 729009
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 99e3eee7f7d41884c9928eefdcd68afd
folderAsset: yes
timeCreated: 1490213953
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,59 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1001 &2324463433763239801
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
serializedVersion: 3
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 100002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_Name
value: Drill
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400002, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects: []
m_AddedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 004a97f809c2c7c40b973eabe880a410, type: 3}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: f5a2d19d564785d45a6207078113bcaa
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 86242
packageName: Workplace Tools
packageVersion: 1.2
assetPath: Assets/Workplace Tools/Prefabs/Drill.prefab
uploadId: 729009
@@ -0,0 +1,59 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1001 &681709522215140374
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
serializedVersion: 3
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 100000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_Name
value: Wrench_Combination
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalRotation.w
value: 1
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalRotation.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalRotation.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: 400000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects: []
m_AddedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 36b5cba1111e25849b7ad46d9ad3f85e, type: 3}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: e2213544abe0a9548a2bf8428f0a1a78
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 86242
packageName: Workplace Tools
packageVersion: 1.2
assetPath: Assets/Workplace Tools/Prefabs/Wrench_Combination.prefab
uploadId: 729009
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -126,7 +126,7 @@ ModelImporter:
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations: []
isReadable: 0
isReadable: 1
meshes:
lODScreenPercentages: []
globalScale: 1
+11 -3
View File
@@ -1,23 +1,31 @@
{
"packages": {
"com.IvanMurzak.McpPlugin": {
"version": "8.6.0",
"version": "8.9.0",
"dlls": [
"McpPlugin.dll"
]
},
"com.IvanMurzak.McpPlugin.Common": {
"version": "8.6.0",
"version": "8.9.0",
"dlls": [
"McpPlugin.Common.dll"
]
},
"com.IvanMurzak.ReflectorNet": {
"version": "5.4.1",
"version": "5.4.2",
"dlls": [
"ReflectorNet.dll"
]
},
"com.IvanMurzak.Rql": {
"version": "0.1.1",
"dlls": [
"Rql.Contracts.dll",
"Rql.Execution.dll",
"Rql.Parser.dll"
]
},
"Microsoft.AspNetCore.Connections.Abstractions": {
"version": "8.0.15",
"dlls": [
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,27 @@
fileFormatVersion: 2
guid: 113d3bf114506414d8951305af3cc563
PluginImporter:
externalObjects: {}
serializedVersion: 3
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
Any:
enabled: 0
settings: {}
Editor:
enabled: 1
settings:
DefaultValueInitialized: true
WindowsStoreApps:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.
@@ -0,0 +1,27 @@
fileFormatVersion: 2
guid: 35fcb14673027f84fb0e7e939a428990
PluginImporter:
externalObjects: {}
serializedVersion: 3
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
Any:
enabled: 0
settings: {}
Editor:
enabled: 1
settings:
DefaultValueInitialized: true
WindowsStoreApps:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.
+27
View File
@@ -0,0 +1,27 @@
fileFormatVersion: 2
guid: b3e011a14585afd409a8f612c4f2e666
PluginImporter:
externalObjects: {}
serializedVersion: 3
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
Any:
enabled: 0
settings: {}
Editor:
enabled: 1
settings:
DefaultValueInitialized: true
WindowsStoreApps:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large. Load diff
@@ -6,16 +6,15 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
[SerializeField] private Transform exitPoint;
[SerializeField] private UIManager uiManager;
private CarOrbitCamera globalCarCamera; // Ссылка на глобальную камеру
private CarOrbitCamera globalCarCamera;
private CarController carController;
private GameObject playerInstance;
public bool isPlayerInside = false;
[HideInInspector] public bool isPlayerInside;
private void Awake()
{
carController = GetComponent<CarController>();
// Автоматически находим камеру на сцене, даже если она выключена
carController = GetComponent<CarController>() ?? GetComponentInChildren<CarController>() ?? GetComponentInParent<CarController>();
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
globalCarCamera = FindAnyObjectByType<CarOrbitCamera>(FindObjectsInactive.Include);
}
@@ -24,10 +23,7 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
if (!isPlayerInside) EnterVehicle(interactor);
}
public string GetPrompt()
{
return "Сесть в машину (E)";
}
public string GetPrompt() => "[F] Сесть в машину";
private void EnterVehicle(GameObject player)
{
@@ -35,22 +31,24 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
playerInstance = player;
playerInstance.SetActive(false);
// Передаем этой машине фокус и включаем камеру
if (globalCarCamera != null)
{
globalCarCamera.SetTarget(transform);
globalCarCamera.gameObject.SetActive(true);
}
if (uiManager != null) uiManager.ToggleDashboard(true);
if (uiManager != null)
{
uiManager.HidePrompt();
uiManager.ToggleDashboard(true);
}
}
private void ExitVehicle()
{
isPlayerInside = false;
carController.ProcessInput(0f, 0f, true);
if (carController != null) carController.ProcessInput(0f, 0f, true);
// Отвязываем цель и выключаем камеру авто
if (globalCarCamera != null)
{
globalCarCamera.SetTarget(null);
@@ -62,7 +60,10 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
CharacterController charController = playerInstance.GetComponent<CharacterController>();
if (charController != null) charController.enabled = false;
if (exitPoint != null)
playerInstance.transform.position = exitPoint.position;
else
playerInstance.transform.position = transform.position - transform.right * 1.8f + Vector3.up * 0.5f;
if (charController != null) charController.enabled = true;
@@ -74,14 +75,17 @@ public class VehicleInteraction : MonoBehaviour, IInteractable
{
if (!isPlayerInside) return;
if (carController != null)
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
bool isBraking = Input.GetKey(KeyCode.Space);
carController.ProcessInput(vertical, horizontal, isBraking);
if (uiManager != null) uiManager.UpdateSpeed(carController.SpeedKmH);
}
if (Input.GetKeyDown(KeyCode.E)) ExitVehicle();
if (Input.GetKeyDown(KeyCode.F) || Input.GetKeyDown(KeyCode.E))
ExitVehicle();
}
}
+237 -254
View File
@@ -7,10 +7,9 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
[Header("Данные")]
[SerializeField] private CarPartData partData;
[SerializeField] private float mass = 12f;
[Header("Позиционирование в руках")]
[Tooltip("Дополнительное смещение детали в руках, если она перекрывает весь обзор")]
[SerializeField] private Vector3 inHandPositionOffset = Vector3.zero;
[Tooltip("Поворот детали в руках (например, если бампер берется боком)")]
[SerializeField] private Vector3 inHandRotationOffset = Vector3.zero;
private CarPartAnimator partAnimator;
@@ -21,271 +20,25 @@ public class CarPart : MonoBehaviour, IInteractable, ISecondaryInteractable
private Vector3 originalLocalScale;
private WheelBolt[] wheelBolts;
private Rigidbody rb;
private Collider partCollider;
private GameObject currentMountZone;
private WheelCollider linkedWheelCollider;
private Transform currentHoldPoint;
private Vector3 targetInHandLocalPos;
private Quaternion targetInHandLocalRot;
private Rigidbody rb;
private Collider partCollider;
private GameObject currentMountZone;
private float unboltDuration => (partData != null && partData.boltDuration > 0f) ? partData.boltDuration : 1.2f;
private float unboltProgress = 0f;
public float UnboltProgress01 => Mathf.Clamp01(unboltProgress / unboltDuration);
public float UnboltProgress01 => Mathf.Clamp01(unboltProgress / unboltDuration);
public void ResetUnbolt() => unboltProgress = 0f;
public CarPartData Data => partData;
public PartState State => currentState;
public bool HasAnimator => partAnimator != null;
public int TotalBoltsCount => wheelBolts != null ? wheelBolts.Length : 0;
private void Awake()
{
partCollider = GetComponent<Collider>();
partAnimator = GetComponent<CarPartAnimator>();
wheelBolts = GetComponentsInChildren<WheelBolt>(true);
originalParent = transform.parent;
originalLocalPos = transform.localPosition;
originalLocalRot = transform.localRotation;
originalLocalScale = transform.localScale;
// Если эта деталь — колесо, автоматически находим её физический WheelCollider по имени (например, "Wheel_FL")
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
if (car != null)
{
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(true))
{
if (wc.name == gameObject.name)
{
linkedWheelCollider = wc;
break;
}
}
}
}
public string GetPrompt()
{
if (partData == null) return "Деталь (E)";
if (currentState == PartState.Installed)
{
if (wheelBolts != null && wheelBolts.Length > 0 && !CarJack.IsWheelLifted(transform))
{
return "Колесо под нагрузкой! Сначала поднимите авто домкратом";
}
if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount > 0)
{
return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})";
}
if (unboltProgress > 0f)
{
return $"Откручивание болтов ({partData.partName})... {Mathf.RoundToInt(UnboltProgress01 * 100f)}%";
}
if (partAnimator != null)
{
string action = partAnimator.IsOpen ? "Закрыть" : "Открыть";
return $"[E] {action} {partData.partName} | [R] Снять";
}
return $"Снять {partData.partName} (E)";
}
if (currentState == PartState.Dropped)
{
return $"Взять {partData.partName} (E)";
}
return string.Empty;
}
public void Interact(GameObject interactor)
{
if (currentState == PartState.Installed)
{
if (partAnimator != null)
{
// Нажали E — открываем или закрываем
partAnimator.TogglePart();
}
else
{
// Обычная деталь (бампер) сразу снимается
TakeToHands(interactor);
}
}
else if (currentState == PartState.Dropped)
{
TakeToHands(interactor);
}
}
// Вызывается при нажатии R (вторичное действие)
public void SecondaryInteract(GameObject interactor)
{
if (currentState == PartState.Installed)
{
TakeToHands(interactor);
}
}
// Вынесенный общий метод взятия в руки
private void TakeToHands(GameObject interactor)
{
PlayerHands hands = interactor.GetComponent<PlayerHands>();
if (hands == null) hands = interactor.GetComponentInParent<PlayerHands>();
if (hands == null) return;
if (currentState == PartState.Installed)
{
if (partAnimator != null) partAnimator.ResetToClosed();
CreateMountZone();
}
hands.PickUp(this);
}
private void LateUpdate()
{
// Блокируем попытки скрипта подвески (EasySuspension) вернуть снятое колесо обратно на машину
if (currentState == PartState.InHand && currentHoldPoint != null)
{
transform.localPosition = targetInHandLocalPos;
transform.localRotation = targetInHandLocalRot;
}
}
public void OnPickedUp(Transform holdPoint)
{
currentState = PartState.InHand;
currentHoldPoint = holdPoint;
if (rb != null) Destroy(rb);
if (partCollider != null) partCollider.enabled = false;
// Если сняли колесо — выключаем его физический WheelCollider на машине
if (linkedWheelCollider != null)
linkedWheelCollider.enabled = false;
transform.SetParent(holdPoint);
transform.localScale = originalLocalScale;
transform.localRotation = Quaternion.Euler(inHandRotationOffset);
transform.localPosition = Vector3.zero;
Renderer meshRenderer = GetComponentInChildren<Renderer>();
if (meshRenderer != null)
{
Vector3 visualCenterWorld = meshRenderer.bounds.center;
Vector3 offsetToCenter = holdPoint.position - visualCenterWorld;
transform.position += offsetToCenter;
transform.localPosition += inHandPositionOffset;
}
// Запоминаем вычисленную позицию в руках для удержания в LateUpdate
targetInHandLocalPos = transform.localPosition;
targetInHandLocalRot = transform.localRotation;
}
public void OnDropped(Vector3 throwForce)
{
currentState = PartState.Dropped;
// Гарантируем, что деталь вылетает именно из точки рук перед игроком, а не из арки авто
if (currentHoldPoint != null)
{
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.4f;
}
currentHoldPoint = null;
transform.SetParent(null);
transform.localScale = originalLocalScale;
if (partCollider != null)
{
partCollider.enabled = true;
if (partCollider is MeshCollider meshCol) meshCol.convex = true;
}
rb = gameObject.AddComponent<Rigidbody>();
rb.mass = mass;
rb.interpolation = RigidbodyInterpolation.Interpolate;
if (throwForce != Vector3.zero)
{
rb.AddForce(throwForce, ForceMode.Impulse);
}
}
public void Install()
{
currentState = PartState.Installed;
currentHoldPoint = null;
if (rb != null) Destroy(rb);
transform.SetParent(originalParent);
transform.localPosition = originalLocalPos;
transform.localRotation = originalLocalRot;
transform.localScale = originalLocalScale;
if (partCollider != null) partCollider.enabled = true;
// Включаем обратно физический WheelCollider при установке колеса
if (linkedWheelCollider != null)
linkedWheelCollider.enabled = true;
}
private void CreateMountZone()
{
if (currentMountZone != null) return;
currentMountZone = new GameObject($"MountZone_{gameObject.name}");
currentMountZone.transform.SetParent(originalParent);
currentMountZone.transform.localPosition = originalLocalPos;
currentMountZone.transform.localRotation = originalLocalRot;
currentMountZone.transform.localScale = originalLocalScale; // Передаем оригинальный масштаб
CarPartMountZone zone = currentMountZone.AddComponent<CarPartMountZone>();
zone.Initialize(this);
}
public void ProcessUnbolting(GameObject interactor, float deltaTime)
{
if (wheelBolts != null && wheelBolts.Length > 0 && !CarJack.IsWheelLifted(transform)) return;
if (currentState != PartState.Installed) return;
if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount > 0) return;
// Если у детали есть отдельные болты и они УЖЕ выкручены — снимаем колесо сразу без повторного таймера!
if (wheelBolts != null && wheelBolts.Length > 0)
{
TakeToHands(interactor);
return;
}
// Не даем снимать детали, если в руках шлифмашинка или баллончик
PlayerToolManager toolMgr = interactor.GetComponentInChildren<PlayerToolManager>();
if (toolMgr != null && toolMgr.currentTool != ToolType.Hands) return;
unboltProgress += deltaTime;
if (unboltProgress >= unboltDuration)
{
unboltProgress = 0f;
TakeToHands(interactor);
}
}
public int TightenedBoltsCount
{
get
@@ -297,4 +50,234 @@ private void LateUpdate()
return count;
}
}
private void Awake()
{
partCollider = GetComponent<Collider>();
partAnimator = GetComponent<CarPartAnimator>();
wheelBolts = GetComponentsInChildren<WheelBolt>(true);
originalParent = transform.parent;
originalLocalPos = transform.localPosition;
originalLocalRot = transform.localRotation;
originalLocalScale = transform.localScale;
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
if (car != null)
{
foreach (WheelCollider wc in car.GetComponentsInChildren<WheelCollider>(true))
{
if (wc.name == gameObject.name)
{
linkedWheelCollider = wc;
break;
}
}
}
// ВАЖНО: Если это колесо, на машине его MeshCollider ДОЛЖЕН быть триггером!
// Иначе он трется об асфальт и крылья машины, мешая WheelCollider'у ехать!
if (linkedWheelCollider != null && partCollider != null)
{
if (partCollider is MeshCollider mc) mc.convex = true;
partCollider.isTrigger = true;
}
}
private void LateUpdate()
{
if (currentState == PartState.InHand && currentHoldPoint != null)
{
transform.localPosition = targetInHandLocalPos;
transform.localRotation = targetInHandLocalRot;
}
}
public string GetPrompt()
{
if (partData == null) return "Деталь (E)";
if (currentState == PartState.Installed)
{
if (wheelBolts != null && wheelBolts.Length > 0)
{
if (!CarJack.IsWheelLifted(transform))
return "Колесо под нагрузкой! Поднимите авто домкратом";
if (TightenedBoltsCount > 0)
return $"Сначала открутите болты ({TightenedBoltsCount}/{wheelBolts.Length})";
return $"[E] Снять {partData.partName}";
}
if (unboltProgress > 0f)
return $"Откручивание болтов ({partData.partName})... {Mathf.RoundToInt(UnboltProgress01 * 100f)}%";
if (partAnimator != null)
{
string action = partAnimator.IsOpen ? "Закрыть" : "Открыть";
return $"[E] {action} {partData.partName} | [Удерж. R] Снять";
}
return $"[Удерж. E] Снять {partData.partName}";
}
if (currentState == PartState.Dropped)
return $"[E] Взять {partData.partName}";
return string.Empty;
}
public void Interact(GameObject interactor)
{
if (currentState == PartState.Installed)
{
if (partAnimator != null)
partAnimator.TogglePart();
else if (wheelBolts != null && wheelBolts.Length > 0 && TightenedBoltsCount == 0 && CarJack.IsWheelLifted(transform))
TakeToHands(interactor);
}
else if (currentState == PartState.Dropped)
{
TakeToHands(interactor);
}
}
public void SecondaryInteract(GameObject interactor) { }
public void ProcessUnbolting(GameObject interactor, float deltaTime)
{
if (currentState != PartState.Installed) return;
if (wheelBolts != null && wheelBolts.Length > 0)
{
if (!CarJack.IsWheelLifted(transform) || TightenedBoltsCount > 0) return;
TakeToHands(interactor);
return;
}
PlayerToolManager toolMgr = interactor.GetComponentInChildren<PlayerToolManager>();
if (toolMgr != null && toolMgr.currentTool != ToolType.Hands) return;
unboltProgress += deltaTime;
if (unboltProgress >= unboltDuration)
{
unboltProgress = 0f;
TakeToHands(interactor);
}
}
private void TakeToHands(GameObject interactor)
{
PlayerHands hands = interactor.GetComponentInChildren<PlayerHands>() ?? interactor.GetComponentInParent<PlayerHands>();
if (hands == null || hands.IsHolding) return;
if (currentState == PartState.Installed)
{
if (partAnimator != null) partAnimator.ResetToClosed();
CreateMountZone();
}
hands.PickUp(this);
}
public void OnPickedUp(Transform holdPoint)
{
currentState = PartState.InHand;
currentHoldPoint = holdPoint;
unboltProgress = 0f;
if (rb != null) Destroy(rb);
if (partCollider != null) partCollider.enabled = false;
if (linkedWheelCollider != null)
linkedWheelCollider.enabled = false;
transform.SetParent(holdPoint);
transform.localScale = originalLocalScale;
transform.localRotation = Quaternion.Euler(inHandRotationOffset);
transform.localPosition = Vector3.zero;
Renderer meshRenderer = GetComponentInChildren<Renderer>();
if (meshRenderer != null)
{
Vector3 visualCenterWorld = meshRenderer.bounds.center;
Vector3 offsetToCenter = holdPoint.position - visualCenterWorld;
transform.position += offsetToCenter;
transform.localPosition += inHandPositionOffset;
}
targetInHandLocalPos = transform.localPosition;
targetInHandLocalRot = transform.localRotation;
}
public void OnDropped(Vector3 throwForce)
{
currentState = PartState.Dropped;
unboltProgress = 0f;
if (currentHoldPoint != null)
transform.position = currentHoldPoint.position + currentHoldPoint.forward * 0.45f;
currentHoldPoint = null;
transform.SetParent(null);
transform.localScale = originalLocalScale;
if (partCollider != null)
{
if (partCollider is MeshCollider meshCol) meshCol.convex = true;
partCollider.isTrigger = false; // На земле деталь твердая
partCollider.enabled = true;
}
rb = gameObject.AddComponent<Rigidbody>();
rb.mass = mass;
rb.interpolation = RigidbodyInterpolation.Interpolate;
if (throwForce != Vector3.zero)
rb.AddForce(throwForce, ForceMode.Impulse);
}
public void Install()
{
currentState = PartState.Installed;
currentHoldPoint = null;
unboltProgress = 0f;
if (rb != null) Destroy(rb);
transform.SetParent(originalParent);
transform.localPosition = originalLocalPos;
transform.localRotation = originalLocalRot;
transform.localScale = originalLocalScale;
if (partCollider != null)
{
partCollider.enabled = true;
// Установленное колесо делаем триггером, чтобы оно не мешало физике езды!
if (linkedWheelCollider != null)
partCollider.isTrigger = true;
}
if (linkedWheelCollider != null)
{
linkedWheelCollider.enabled = true;
linkedWheelCollider.motorTorque = 0f;
linkedWheelCollider.brakeTorque = 0f;
}
}
private void CreateMountZone()
{
if (currentMountZone != null) return;
currentMountZone = new GameObject($"MountZone_{gameObject.name}");
currentMountZone.transform.SetParent(originalParent);
currentMountZone.transform.localPosition = originalLocalPos;
currentMountZone.transform.localRotation = originalLocalRot;
currentMountZone.transform.localScale = originalLocalScale;
CarPartMountZone zone = currentMountZone.AddComponent<CarPartMountZone>();
zone.Initialize(this);
}
}
+18 -10
View File
@@ -17,14 +17,25 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
gameObject.layer = part.gameObject.layer;
cachedHands = FindAnyObjectByType<PlayerHands>();
// Проверяем, есть ли у детали собственные физические болты (например, у колеса)
hasSeparateBolts = part.GetComponentsInChildren<WheelBolt>(true).Length > 0;
if (part.Data != null && part.Data.boltDuration > 0f)
mountDuration = part.Data.boltDuration;
// 1. Копируем коллайдер детали
MeshFilter sourceFilter = part.GetComponentInChildren<MeshFilter>();
// Для колеса создаем удобную широкую сферу вокруг ступицы, чтобы луч всегда попадал с первого раза
if (hasSeparateBolts)
{
SphereCollider sphere = gameObject.AddComponent<SphereCollider>();
if (sourceFilter != null && sourceFilter.sharedMesh != null)
sphere.center = sourceFilter.sharedMesh.bounds.center;
sphere.radius = 0.48f;
sphere.isTrigger = true;
zoneCollider = sphere;
}
else
{
Collider sourceCollider = part.GetComponent<Collider>();
if (sourceCollider is BoxCollider sourceBox)
{
@@ -49,9 +60,8 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
sphere.isTrigger = true;
zoneCollider = sphere;
}
}
// 2. Создаем 3D-силуэт (Ghost) места установки из CarPartData
MeshFilter sourceFilter = part.GetComponentInChildren<MeshFilter>();
if (sourceFilter != null && sourceFilter.sharedMesh != null)
{
MeshFilter mf = gameObject.AddComponent<MeshFilter>();
@@ -106,18 +116,17 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
string partTitle = targetPart.Data != null ? targetPart.Data.partName : "Деталь";
// Если у детали есть отдельные болты (колесо) — ставим на ступицу сразу по нажатию E
// Колесо надевается на ступицу сразу при нажатии E или ЛКМ
if (hasSeparateBolts)
{
if (Input.GetKeyDown(KeyCode.E))
if (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0))
{
CompleteInstall();
return string.Empty;
}
return $"[E] Надеть {partTitle} на ступицу";
return $"[E / ЛКМ] Надеть {partTitle} на ступицу";
}
// Для остальных деталей (бамперы, крылья, капот) — закручиваем болты удержанием E
if (Input.GetKey(KeyCode.E))
{
currentMountProgress += Time.deltaTime;
@@ -140,7 +149,6 @@ public class CarPartMountZone : MonoBehaviour, IInteractable
public void Interact(GameObject interactor)
{
// Если PlayerInteractor вызвал одиночный клик для колеса — сразу надеваем его
if (hasSeparateBolts && cachedHands != null && cachedHands.IsHolding && cachedHands.CurrentPart == targetPart)
{
CompleteInstall();
@@ -1,170 +0,0 @@
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class AdvancedCarController : MonoBehaviour
{
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
[Header("Данные авто")]
[SerializeField] private CarPhysicsData data;
[Header("Колеса (WheelColliders)")]
[SerializeField] private WheelCollider[] frontWheels;
[SerializeField] private WheelCollider[] rearWheels;
[Header("Состояние деталей (Для диплома)")]
[Range(0.1f, 1f)] public float engineCondition = 1f; // 1 - новое, 0.1 - убитое (не тянет)
[Range(0.1f, 1f)] public float tiresCondition = 1f; // Влияет на держак резины
// Состояние авто
public float CurrentSpeedKmH => rb.linearVelocity.magnitude * 3.6f;
public float EngineRPM { get; private set; }
public int CurrentGear { get; private set; }
private Rigidbody rb;
private float currentSteerAngle;
private WheelFrictionCurve originalRearSidewaysFriction;
// Ввод
private float moveInput, steerInput;
private bool isBraking, isHandbrake;
private void Awake()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = data.centerOfMassOffset; // Понижаем центр масс для стабильности
// Запоминаем оригинальное трение для ручника
if (rearWheels.Length > 0)
originalRearSidewaysFriction = rearWheels[0].sidewaysFriction;
}
private void Update()
{
// Чтение инпута (можно заменить на новый Input System)
moveInput = Input.GetAxis("Vertical");
steerInput = Input.GetAxis("Horizontal");
isBraking = Input.GetKey(KeyCode.Space) || (moveInput < 0 && CurrentSpeedKmH > 5f);
isHandbrake = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.Space);
}
private void FixedUpdate()
{
ApplySteering();
ProcessEngineAndGears();
ApplyAntiRollBar();
ProcessHandbrake();
}
public void ProcessInput(float vertical, float horizontal, bool handbrake)
{
moveInput = vertical;
steerInput = horizontal;
isHandbrake = handbrake;
}
private void ApplySteering()
{
// 1. Угол зависит от скорости (на 100 км/ч руль не вывернется на 35 градусов)
float speedMultiplier = data.steerAngleBySpeed.Evaluate(CurrentSpeedKmH);
float targetSteer = steerInput * data.maxSteerAngle * speedMultiplier;
// 2. Сглаживание поворота (руль не дергается мгновенно)
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * data.steerSmoothing);
foreach (var wheel in frontWheels)
{
wheel.steerAngle = currentSteerAngle;
}
}
private void ProcessEngineAndGears()
{
// Считаем средние обороты ведущих колес (допустим, задний привод)
float wheelRPM = 0;
foreach (var w in rearWheels) wheelRPM += Mathf.Abs(w.rpm);
wheelRPM /= rearWheels.Length;
// Вычисляем обороты двигателя через передаточные числа
float gearRatio = data.gearRatios[CurrentGear];
EngineRPM = Mathf.Clamp(wheelRPM * gearRatio * data.finalDrive, data.minRPM, data.maxRPM);
// Автоматическая коробка передач
if (EngineRPM > data.shiftUpRPM && CurrentGear < data.gearRatios.Length - 1)
CurrentGear++;
else if (EngineRPM < data.shiftDownRPM && CurrentGear > 0)
CurrentGear--;
// Получаем крутящий момент по графику и умножаем на состояние двигателя!
float motorTorque = data.torqueCurve.Evaluate(EngineRPM) * gearRatio * data.finalDrive;
float finalTorque = moveInput * motorTorque * engineCondition;
// Применяем газ или тормоз
foreach (var wheel in rearWheels)
{
if (isBraking)
{
wheel.motorTorque = 0;
wheel.brakeTorque = data.brakeForce;
}
else
{
wheel.motorTorque = finalTorque / rearWheels.Length;
wheel.brakeTorque = 0;
}
}
}
private void ProcessHandbrake()
{
foreach (var wheel in rearWheels)
{
if (isHandbrake)
{
wheel.brakeTorque = data.brakeForce;
// ДРИФТ: Уменьшаем боковое сцепление, умножая на износ шин
WheelFrictionCurve fc = wheel.sidewaysFriction;
fc.stiffness = originalRearSidewaysFriction.stiffness * data.handbrakeFrictionMultiplier * tiresCondition;
wheel.sidewaysFriction = fc;
}
else if (!isBraking)
{
wheel.brakeTorque = 0;
// Возвращаем обычное сцепление с поправкой на убитость шин
WheelFrictionCurve fc = wheel.sidewaysFriction;
fc.stiffness = originalRearSidewaysFriction.stiffness * tiresCondition;
wheel.sidewaysFriction = fc;
}
}
}
private void ApplyAntiRollBar()
{
// Стабилизатор поперечной устойчивости для передней и задней оси
ApplyAxleAntiRoll(frontWheels[0], frontWheels[1]);
ApplyAxleAntiRoll(rearWheels[0], rearWheels[1]);
}
private void ApplyAxleAntiRoll(WheelCollider left, WheelCollider right)
{
float travelL = 1.0f;
float travelR = 1.0f;
bool groundedL = left.GetGroundHit(out WheelHit hitL);
if (groundedL) travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
bool groundedR = right.GetGroundHit(out WheelHit hitR);
if (groundedR) travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
// Разница сжатия подвески
float antiRollVal = (travelL - travelR) * data.antiRollForce;
// Применяем противодействующую силу (прижимаем поднявшееся колесо)
if (groundedL) rb.AddForceAtPosition(left.transform.up * -antiRollVal, left.transform.position);
if (groundedR) rb.AddForceAtPosition(right.transform.up * antiRollVal, right.transform.position);
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: c02b03f912164de9ae5c7659d886fae9
timeCreated: 1791809782
+160 -115
View File
@@ -2,28 +2,28 @@ using UnityEngine;
public enum DriveType { FWD, RWD, AWD }
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour
{
public float SpeedKmH => rb.linearVelocity.magnitude * 3.6f;
public float SpeedKmH => rb != null ? rb.linearVelocity.magnitude * 3.6f : 0f;
[Header("Drive Settings")]
[Header("Аркадные настройки движения")]
public DriveType driveType = DriveType.AWD;
[SerializeField] private float motorForce = 1500f;
[SerializeField] private float brakeForce = 3000f;
[SerializeField] private float maxSteerAngle = 30f;
[SerializeField] private float motorForce = 2200f;
[SerializeField] private float maxSpeedKmH = 160f;
[SerializeField] private float brakeForce = 4500f;
[Header("Grip Settings (Friction Stiffness)")]
[Tooltip("Сцепление для переднего привода (FWD)")]
[SerializeField] private float fwdFrontGrip = 1.2f;
[SerializeField] private float fwdRearGrip = 2.0f;
[Header("Рулевое управление")]
[SerializeField] private float maxSteerAngle = 32f;
[SerializeField] private float steerSpeed = 8f;
[Tooltip("Во сколько раз уменьшается выворот руля на максимальной скорости")]
[SerializeField] private float highSpeedSteerFactor = 0.35f;
[Tooltip("Сцепление для заднего привода (RWD)")]
[SerializeField] private float rwdFrontGrip = 2.0f;
[SerializeField] private float rwdRearGrip = 1.2f;
[Tooltip("Сцепление для полного привода (AWD)")]
[SerializeField] private float awdFrontGrip = 2.5f;
[SerializeField] private float awdRearGrip = 2.5f;
[Header("Устойчивость и Дрифт")]
[SerializeField] private Vector3 centerOfMassOffset = new Vector3(0f, -0.45f, 0f);
[SerializeField] private float antiRollForce = 8000f;
[SerializeField] private float normalGrip = 2.2f;
[SerializeField] private float handbrakeRearGrip = 0.65f;
[Header("Wheel Colliders")]
[SerializeField] private WheelCollider frontLeftCollider;
@@ -38,15 +38,41 @@ public class CarController : MonoBehaviour
[SerializeField] private Transform rearRightMesh;
private Rigidbody rb;
// Входящие данные от игрока
private float inputVertical;
private float inputHorizontal;
private bool inputHandbrake;
private float currentSteerAngle;
private void Start()
private void Awake()
{
rb = GetComponent<Rigidbody>();
rb.centerOfMass = centerOfMassOffset;
rb.angularDamping = 1.5f;
SetupArcadeWheel(frontLeftCollider);
SetupArcadeWheel(frontRightCollider);
SetupArcadeWheel(rearLeftCollider);
SetupArcadeWheel(rearRightCollider);
}
private void SetupArcadeWheel(WheelCollider wc)
{
if (wc == null) return;
JointSpring spring = wc.suspensionSpring;
spring.spring = 35000f;
spring.damper = 4500f;
spring.targetPosition = 0.5f;
wc.suspensionSpring = spring;
wc.suspensionDistance = 0.18f;
WheelFrictionCurve fwd = wc.forwardFriction;
fwd.stiffness = 2.0f;
wc.forwardFriction = fwd;
WheelFrictionCurve side = wc.sidewaysFriction;
side.stiffness = normalGrip;
wc.sidewaysFriction = side;
}
public void ProcessInput(float vertical, float horizontal, bool handbrake)
@@ -60,117 +86,138 @@ public class CarController : MonoBehaviour
{
HandleSteering();
HandleMotorAndBrakes();
ApplyAntiRoll(frontLeftCollider, frontRightCollider);
ApplyAntiRoll(rearLeftCollider, rearRightCollider);
UpdateWheelPoses();
}
private void HandleSteering()
{
float steerAngle = maxSteerAngle * inputHorizontal;
frontLeftCollider.steerAngle = steerAngle;
frontRightCollider.steerAngle = steerAngle;
float speedFactor = Mathf.Lerp(1f, highSpeedSteerFactor, SpeedKmH / maxSpeedKmH);
float targetSteer = inputHorizontal * maxSteerAngle * speedFactor;
currentSteerAngle = Mathf.Lerp(currentSteerAngle, targetSteer, Time.fixedDeltaTime * steerSpeed);
if (frontLeftCollider != null) frontLeftCollider.steerAngle = currentSteerAngle;
if (frontRightCollider != null) frontRightCollider.steerAngle = currentSteerAngle;
}
private void HandleMotorAndBrakes()
{
float currentMotorTorque = 0f;
float currentBrakeTorque = 0f;
float localVelZ = transform.InverseTransformDirection(rb.linearVelocity).z;
float motor = 0f;
float brake = 0f;
// Определяем, куда физически движется машина (вперед или назад)
float localVelocityZ = transform.InverseTransformDirection(rb.linearVelocity).z;
// ЛОГИКА ГАЗА (W)
if (inputVertical > 0)
if (inputVertical > 0.01f)
{
if (localVelocityZ < -1f) // Если катимся назад, а жмем W -> Тормозим
currentBrakeTorque = brakeForce;
else // Иначе едем вперед
currentMotorTorque = inputVertical * motorForce;
if (localVelZ < -1.5f)
brake = brakeForce;
else if (SpeedKmH < maxSpeedKmH)
motor = inputVertical * motorForce;
}
// ЛОГИКА ТОРМОЗА И ЗАДНЕГО ХОДА (S)
else if (inputVertical < 0)
else if (inputVertical < -0.01f)
{
if (localVelocityZ > 1f) // Если едем вперед, а жмем S -> Тормозим
currentBrakeTorque = brakeForce;
else // Иначе сдаем назад (inputVertical отрицательный, поэтому момент тоже отрицательный)
currentMotorTorque = inputVertical * motorForce;
}
// ЛОГИКА РУЧНИКА (Пробел)
if (inputHandbrake)
{
currentMotorTorque = 0f; // Глушим газ
currentBrakeTorque = brakeForce * 2f; // Ручник хватает сильнее обычного тормоза
}
ApplyBrakes(currentBrakeTorque, inputHandbrake);
ApplyMotor(currentMotorTorque);
}
private void ApplyMotor(float torque)
{
// Получаем базовые настройки трения
WheelFrictionCurve frontFriction = frontLeftCollider.sidewaysFriction;
WheelFrictionCurve rearFriction = rearLeftCollider.sidewaysFriction;
switch (driveType)
{
case DriveType.FWD:
frontLeftCollider.motorTorque = torque;
frontRightCollider.motorTorque = torque;
rearLeftCollider.motorTorque = 0;
rearRightCollider.motorTorque = 0;
frontFriction.stiffness = fwdFrontGrip;
rearFriction.stiffness = fwdRearGrip;
break;
case DriveType.RWD:
frontLeftCollider.motorTorque = 0;
frontRightCollider.motorTorque = 0;
rearLeftCollider.motorTorque = torque;
rearRightCollider.motorTorque = torque;
frontFriction.stiffness = rwdFrontGrip;
rearFriction.stiffness = rwdRearGrip;
break;
case DriveType.AWD:
float halfTorque = torque / 2f;
frontLeftCollider.motorTorque = halfTorque;
frontRightCollider.motorTorque = halfTorque;
rearLeftCollider.motorTorque = halfTorque;
rearRightCollider.motorTorque = halfTorque;
frontFriction.stiffness = awdFrontGrip;
rearFriction.stiffness = awdRearGrip;
break;
}
// Применяем измененное трение к колесам
frontLeftCollider.sidewaysFriction = frontFriction;
frontRightCollider.sidewaysFriction = frontFriction;
rearLeftCollider.sidewaysFriction = rearFriction;
rearRightCollider.sidewaysFriction = rearFriction;
}
private void ApplyBrakes(float brake, bool isHandbrake)
{
if (isHandbrake)
{
// Ручник блокирует только задние колеса (эффект заноса)
frontLeftCollider.brakeTorque = 0;
frontRightCollider.brakeTorque = 0;
rearLeftCollider.brakeTorque = brake;
rearRightCollider.brakeTorque = brake;
if (localVelZ > 1.5f)
brake = brakeForce;
else if (SpeedKmH < 45f)
motor = inputVertical * motorForce * 0.7f;
}
else
{
// Обычный тормоз (S) срабатывает на все колеса, передок сильнее
frontLeftCollider.brakeTorque = brake;
frontRightCollider.brakeTorque = brake;
rearLeftCollider.brakeTorque = brake * 0.5f;
rearRightCollider.brakeTorque = brake * 0.5f;
// Плавное торможение двигателем, когда газ отпущен
brake = 150f;
}
if (inputHandbrake)
{
motor = 0f;
brake = brakeForce * 1.5f;
}
ApplyDriveTorque(motor);
ApplyBrakesAndDrift(brake, inputHandbrake);
}
private void ApplyDriveTorque(float torque)
{
if (driveType == DriveType.FWD)
{
SetMotor(frontLeftCollider, torque);
SetMotor(frontRightCollider, torque);
SetMotor(rearLeftCollider, 0f);
SetMotor(rearRightCollider, 0f);
}
else if (driveType == DriveType.RWD)
{
SetMotor(frontLeftCollider, 0f);
SetMotor(frontRightCollider, 0f);
SetMotor(rearLeftCollider, torque);
SetMotor(rearRightCollider, torque);
}
else
{
float half = torque * 0.55f;
SetMotor(frontLeftCollider, half);
SetMotor(frontRightCollider, half);
SetMotor(rearLeftCollider, half);
SetMotor(rearRightCollider, half);
}
}
private void SetMotor(WheelCollider wc, float val)
{
if (wc != null && wc.enabled) wc.motorTorque = val;
}
private void ApplyBrakesAndDrift(float brake, bool handbrake)
{
float targetRearStiffness = handbrake ? handbrakeRearGrip : normalGrip;
SetRearGrip(rearLeftCollider, targetRearStiffness);
SetRearGrip(rearRightCollider, targetRearStiffness);
if (handbrake)
{
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = 0f;
if (frontRightCollider != null) frontRightCollider.brakeTorque = 0f;
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake;
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake;
}
else
{
if (frontLeftCollider != null) frontLeftCollider.brakeTorque = brake;
if (frontRightCollider != null) frontRightCollider.brakeTorque = brake;
if (rearLeftCollider != null) rearLeftCollider.brakeTorque = brake * 0.6f;
if (rearRightCollider != null) rearRightCollider.brakeTorque = brake * 0.6f;
}
}
private void SetRearGrip(WheelCollider wc, float targetStiff)
{
if (wc == null) return;
WheelFrictionCurve side = wc.sidewaysFriction;
side.stiffness = Mathf.Lerp(side.stiffness, targetStiff, Time.fixedDeltaTime * 10f);
wc.sidewaysFriction = side;
}
private void ApplyAntiRoll(WheelCollider left, WheelCollider right)
{
if (left == null || right == null || !left.enabled || !right.enabled) return;
float travelL = 1f;
float travelR = 1f;
bool groundedL = left.GetGroundHit(out WheelHit hitL);
if (groundedL)
travelL = (-left.transform.InverseTransformPoint(hitL.point).y - left.radius) / left.suspensionDistance;
bool groundedR = right.GetGroundHit(out WheelHit hitR);
if (groundedR)
travelR = (-right.transform.InverseTransformPoint(hitR.point).y - right.radius) / right.suspensionDistance;
float force = (travelL - travelR) * antiRollForce;
if (groundedL) rb.AddForceAtPosition(left.transform.up * -force, left.transform.position);
if (groundedR) rb.AddForceAtPosition(right.transform.up * force, right.transform.position);
}
private void UpdateWheelPoses()
@@ -183,8 +230,6 @@ public class CarController : MonoBehaviour
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
{
// Если меш не назначен, коллайдер выключен или колесо снято с машины
// (больше не является дочерним объектом этого авто) — не двигаем его!
if (mesh == null || collider == null || !collider.enabled || !mesh.IsChildOf(transform))
return;
@@ -1,28 +0,0 @@
using UnityEngine;
[CreateAssetMenu(fileName = "NewCarPhysics", menuName = "Car System/Physics Data")]
public class CarPhysicsData : ScriptableObject
{
[Header("Двигатель и КПП")]
public AnimationCurve torqueCurve; // Кривая: X - обороты (RPM), Y - крутящий момент (Nm)
public float maxRPM = 7000f;
public float minRPM = 800f;
public float shiftUpRPM = 6000f;
public float shiftDownRPM = 2500f;
public float[] gearRatios = { 3.1f, 2.2f, 1.6f, 1.2f, 0.9f, 0.7f };
public float finalDrive = 3.4f;
[Header("Рулевое управление")]
public float maxSteerAngle = 35f;
public float steerSmoothing = 10f; // Скорость поворота руля
[Tooltip("Как сильно режется угол поворота на высокой скорости")]
public AnimationCurve steerAngleBySpeed; // X - скорость (км/ч), Y - множитель угла (0..1)
[Header("Подвеска и физика")]
public Vector3 centerOfMassOffset = new Vector3(0, -0.2f, 0); // Пониженный центр масс
public float antiRollForce = 5000f; // Стабилизатор поперечной устойчивости
public float brakeForce = 3000f;
[Header("Дрифт (Ручник)")]
public float handbrakeFrictionMultiplier = 0.3f; // Насколько скользкой становится задняя ось
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 396086e692304e97aab2b9b09066d2b5
timeCreated: 1791809619
@@ -1,56 +0,0 @@
using UnityEngine;
[ExecuteInEditMode]
public class EasySuspension : MonoBehaviour
{
[Range(0.1f, 20f)] public float naturalFrequency = 10f;
[Range(0.1f, 3f)] public float dampingRatio = 0.8f;
[Range(-1f, 1f)] public float forceShift = 0.03f;
public bool setSuspensionDistance = true;
private WheelCollider[] wheelColliders;
private Rigidbody rb;
private void Awake()
{
CacheComponents();
}
private void CacheComponents()
{
wheelColliders = GetComponentsInChildren<WheelCollider>(true);
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (wheelColliders == null || rb == null)
{
CacheComponents();
if (wheelColliders == null || rb == null) return;
}
foreach (WheelCollider wc in wheelColliders)
{
// ЗАЩИТА: если колесо снято (выключено) или не несет нагрузки — пропускаем, чтобы не делить на 0!
if (wc == null || !wc.enabled || wc.sprungMass <= 0.01f) continue;
JointSpring spring = wc.suspensionSpring;
spring.spring = Mathf.Pow(Mathf.Sqrt(wc.sprungMass) * naturalFrequency, 2);
spring.damper = 2f * dampingRatio * Mathf.Sqrt(spring.spring * wc.sprungMass);
wc.suspensionSpring = spring;
Vector3 wheelRelativeBody = transform.InverseTransformPoint(wc.transform.position);
float distance = rb.centerOfMass.y - wheelRelativeBody.y + wc.radius;
wc.forceAppPointDistance = distance - forceShift;
if (spring.targetPosition > 0.001f && spring.spring > 0.001f && setSuspensionDistance)
{
wc.suspensionDistance = wc.sprungMass * Physics.gravity.magnitude / (spring.targetPosition * spring.spring);
}
}
}
}
@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 4d9eeaad380562f42bac8b304778252c
@@ -1,29 +0,0 @@
using UnityEngine;
public class WheelVisuals : MonoBehaviour
{
[System.Serializable]
public struct WheelPair
{
public WheelCollider collider;
public Transform mesh;
}
[Header("Привязка колес")]
public WheelPair[] wheels;
private void Update()
{
foreach (var w in wheels)
{
if (w.collider == null || w.mesh == null) continue;
// Получаем физическую позицию колеса
w.collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
// Применяем к 3D-модели
w.mesh.position = pos;
w.mesh.rotation = rot;
}
}
}
@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: ce1b65bf09494194a68749d417b0e17a
timeCreated: 1791809850
+239 -200
View File
@@ -13,17 +13,10 @@ public class CarJack : MonoBehaviour, IInteractable
[SerializeField] private Transform screw;
[SerializeField] private Transform topPlate;
[Header("Настройки анимации ромба")]
[Tooltip("Локальная ось вращения лап: (0,0,1), (0,1,0) или (1,0,0)")]
[SerializeField] private Vector3 armRotationAxis = Vector3.forward;
[Tooltip("Локальная ось вращения винта")]
[SerializeField] private Vector3 screwSpinAxis = Vector3.right;
[SerializeField] private float maxFoldAngle = 24f;
[SerializeField] private float liftDuration = 2.5f;
[Header("Настройки подъема авто")]
[Tooltip("На сколько метров поднимается порог после касания домкрата (0.08 = 8 см)")]
[SerializeField] private float carLiftHeight = 0.08f;
[Header("Настройки подъема")]
[SerializeField] private float liftDuration = 2.0f;
[Tooltip("На сколько метров поднимается порог (0.28 = 28 см, чтобы колесо легко вставало на место)")]
[SerializeField] private float carLiftHeight = 0.28f;
[Header("Позиционирование и материалы")]
[SerializeField] private Material ghostMaterial;
@@ -35,33 +28,32 @@ public class CarJack : MonoBehaviour, IInteractable
private JackState currentState = JackState.OnFloor;
private BoxCollider mainCollider;
private Collider[] allJackColliders;
private Rigidbody jackRb;
private Transform holderCamera;
private Transform playerRoot;
private UIManager uiManager;
private int stateChangeFrame = -1;
private Quaternion bArmL_OpenRot, bArmR_OpenRot;
private Quaternion tArmL_OpenRot, tArmR_OpenRot;
private float foldSignL = 1f;
private float foldSignR = -1f;
private float screwSpinAngle = 0f;
private Vector3 originalLocalScale;
private Transform diamondPivot;
private Vector3 topPlateInitLocalPos;
private Vector3 screwInitLocalPos;
private Quaternion screwInitLocalRot;
private Vector3 originalRootScale;
private float modelFullHeight = 0.32f;
private MeshRenderer[] renderers;
private Material[] originalMaterials;
private bool isShowingGhost = false;
// Привязка к автомобилю
// Физический подъемник на базе ConfigurableJoint (дает 100% плавный подъем без дрожи!)
private Rigidbody targetCarRb;
private CarPart targetWheelPart;
private WheelCollider targetWheelCollider;
private WheelCollider[] allCarWheels;
private Vector3 carLocalLiftPoint;
private GameObject supportAnchorObj;
private Rigidbody supportAnchorRb;
private ConfigurableJoint liftJoint;
private float initialSillWorldY;
// Превью установки
private bool canPlaceUnderCar = false;
private Vector3 previewWorldPos;
private Quaternion previewWorldRot;
@@ -72,22 +64,18 @@ public class CarJack : MonoBehaviour, IInteractable
private bool isHoveredThisFrame = false;
public static CarJack ActiveJackInHand { get; private set; }
public JackState State => currentState;
public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.85f;
public bool IsLifted => currentState == JackState.PlacedUnderCar && liftProgress >= 0.70f;
public static bool IsWheelLifted(Transform wheelTransform)
{
if (wheelTransform == null) return false;
CarJack[] allJacks = FindObjectsByType<CarJack>(FindObjectsSortMode.None);
foreach (CarJack jack in allJacks)
{
if (!jack.IsLifted) continue;
if (jack.targetWheelPart != null && jack.targetWheelPart.transform == wheelTransform)
return true;
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 1.8f)
if (Vector3.Distance(jack.transform.position, wheelTransform.position) < 2.0f)
return true;
}
return false;
@@ -96,49 +84,107 @@ public class CarJack : MonoBehaviour, IInteractable
private void Awake()
{
uiManager = FindAnyObjectByType<UIManager>();
originalLocalScale = transform.localScale;
originalRootScale = transform.localScale;
mainCollider = GetComponent<BoxCollider>();
allJackColliders = GetComponentsInChildren<Collider>(true);
// Отключаем лишние дочерние коллайдеры на лапах, оставляя один главный BoxCollider на базе
foreach (var c in allJackColliders)
{
foreach (var c in GetComponentsInChildren<Collider>(true))
if (c != mainCollider) c.enabled = false;
}
renderers = GetComponentsInChildren<MeshRenderer>(true);
originalMaterials = new Material[renderers.Length];
for (int i = 0; i < renderers.Length; i++)
originalMaterials[i] = renderers[i].sharedMaterial;
if (bottomArmL != null && topArmL != null && topArmL.parent != bottomArmL)
topArmL.SetParent(bottomArmL, true);
if (bottomArmR != null && topArmR != null && topArmR.parent != bottomArmR)
topArmR.SetParent(bottomArmR, true);
// Автоматически выравниваем BoxCollider по реальным габаритам модели,
// чтобы его дно не торчало ниже подошвы домкрата
FitColliderToRenderers();
if (bottomArmL != null) bArmL_OpenRot = bottomArmL.localRotation;
if (bottomArmR != null) bArmR_OpenRot = bottomArmR.localRotation;
if (topArmL != null) tArmL_OpenRot = topArmL.localRotation;
if (topArmR != null) tArmR_OpenRot = topArmR.localRotation;
AutoDetectFoldDirections();
SetupUnifiedDiamondRig();
UpdateJackPose();
}
private void AutoDetectFoldDirections()
private void FitColliderToRenderers()
{
if (bottomArmL == null || topArmL == null || bottomArmR == null || topArmR == null) return;
if (mainCollider == null || renderers == null || renderers.Length == 0) return;
float openYL = topArmL.position.y;
bottomArmL.localRotation = bArmL_OpenRot * Quaternion.Euler(armRotationAxis * 5f);
foldSignL = (topArmL.position.y < openYL) ? 1f : -1f;
bottomArmL.localRotation = bArmL_OpenRot;
Quaternion savedRot = transform.rotation;
transform.rotation = Quaternion.identity;
float openYR = topArmR.position.y;
bottomArmR.localRotation = bArmR_OpenRot * Quaternion.Euler(armRotationAxis * 5f);
foldSignR = (topArmR.position.y < openYR) ? 1f : -1f;
bottomArmR.localRotation = bArmR_OpenRot;
Bounds worldBounds = new Bounds(transform.position, Vector3.zero);
bool hasBounds = false;
foreach (var r in renderers)
{
if (r == null) continue;
if (!hasBounds) { worldBounds = r.bounds; hasBounds = true; }
else worldBounds.Encapsulate(r.bounds);
}
if (hasBounds)
{
Vector3 localCenter = transform.InverseTransformPoint(worldBounds.center);
Vector3 localSize = new Vector3(
worldBounds.size.x / Mathf.Max(0.001f, transform.lossyScale.x),
worldBounds.size.y / Mathf.Max(0.001f, transform.lossyScale.y),
worldBounds.size.z / Mathf.Max(0.001f, transform.lossyScale.z)
);
// Задаем минимальную толщину, чтобы физика надежно держала домкрат на асфальте
localSize.x = Mathf.Max(localSize.x, 0.25f);
localSize.y = Mathf.Max(localSize.y, 0.20f);
localSize.z = Mathf.Max(localSize.z, 0.35f);
// Дно коллайдера никогда не опускается ниже 0 (подошвы домкрата)
localCenter.y = Mathf.Max(localCenter.y, localSize.y * 0.5f);
mainCollider.center = localCenter;
mainCollider.size = localSize;
}
transform.rotation = savedRot;
}
private void OnDestroy()
{
DestroyLiftJoint();
}
private void SetupUnifiedDiamondRig()
{
Bounds b = new Bounds(transform.position, Vector3.zero);
bool hasBounds = false;
foreach (var r in renderers)
{
if (r == null) continue;
if (!hasBounds) { b = r.bounds; hasBounds = true; }
else b.Encapsulate(r.bounds);
}
modelFullHeight = hasBounds ? Mathf.Max(0.15f, b.size.y / transform.lossyScale.y) : 0.32f;
GameObject pivotObj = new GameObject("DiamondRigPivot");
diamondPivot = pivotObj.transform;
diamondPivot.SetParent(transform, false);
diamondPivot.localPosition = Vector3.zero;
diamondPivot.localRotation = Quaternion.identity;
diamondPivot.localScale = Vector3.one;
if (bottomArmL != null) bottomArmL.SetParent(diamondPivot, true);
if (bottomArmR != null) bottomArmR.SetParent(diamondPivot, true);
if (topArmL != null) topArmL.SetParent(diamondPivot, true);
if (topArmR != null) topArmR.SetParent(diamondPivot, true);
if (topPlate != null)
{
topPlate.SetParent(transform, true);
topPlateInitLocalPos = topPlate.localPosition;
}
if (screw != null)
{
screw.SetParent(transform, true);
screwInitLocalPos = screw.localPosition;
screwInitLocalRot = screw.localRotation;
}
}
private void Update()
@@ -146,91 +192,100 @@ public class CarJack : MonoBehaviour, IInteractable
if (currentState != JackState.InHand) return;
UpdateInHandPreview();
if (Time.frameCount <= stateChangeFrame) return;
if (canPlaceUnderCar && (Input.GetKeyDown(KeyCode.E) || Input.GetMouseButtonDown(0)))
{
PlaceUnderCar();
}
else if (Input.GetKeyDown(KeyCode.G))
{
DropToFloor();
}
}
private void LateUpdate()
{
if (currentState == JackState.InHand)
{
if (uiManager != null)
uiManager.ShowPrompt(GetPlacementPrompt());
if (uiManager != null) uiManager.ShowPrompt(GetPlacementPrompt());
return;
}
if (currentState == JackState.PlacedUnderCar && isHoveredThisFrame && Time.frameCount > stateChangeFrame)
{
if (Input.GetKey(KeyCode.E))
{
ChangeLift(Time.deltaTime / liftDuration);
}
else if (Input.GetKey(KeyCode.R) && CanLowerSafely())
{
ChangeLift(-Time.deltaTime / liftDuration);
}
else if (liftProgress <= 0.01f && Input.GetKeyDown(KeyCode.G))
{
PickUpToHand(holderCamera, playerRoot);
}
}
isHoveredThisFrame = false;
}
private void FixedUpdate()
{
if (currentState != JackState.PlacedUnderCar || targetCarRb == null) return;
if (currentState != JackState.PlacedUnderCar || targetCarRb == null || supportAnchorRb == null) return;
// До 25% домкрат просто поднимает лапы до касания с порогом (машина стоит на месте!)
if (liftProgress <= 0.25f) return;
// Плавно перемещаем кинематическую точку опоры вверх-вниз вместе с верхушкой домкрата
float targetY = initialSillWorldY + liftProgress * carLiftHeight;
Vector3 targetAnchorPos = new Vector3(transform.position.x, targetY, transform.position.z);
supportAnchorRb.MovePosition(targetAnchorPos);
// Зажимаем тормоза на остальных колесах, чтобы машина не катилась на домкрате
if (allCarWheels != null)
{
foreach (var wc in allCarWheels)
{
if (wc != null && wc.enabled) wc.brakeTorque = 4000f;
}
if (liftProgress > 0.01f)
targetCarRb.WakeUp();
}
// Вычисляем плавный подъем порога строго вместе с верхней площадкой домкрата (topPlate)
float contactFactor = Mathf.InverseLerp(0.25f, 1f, liftProgress);
float targetSillY = topPlate != null
? topPlate.position.y
: (initialSillWorldY + contactFactor * carLiftHeight);
Vector3 currentSillWorld = targetCarRb.transform.TransformPoint(carLocalLiftPoint);
float heightError = targetSillY - currentSillWorld.y;
if (heightError > -0.01f)
private void CreateLiftJoint(Vector3 contactWorld)
{
float pointVelY = targetCarRb.GetPointVelocity(currentSillWorld).y;
float gravity = Physics.gravity.magnitude;
DestroyLiftJoint();
if (targetCarRb == null) return;
// Ограничиваем максимальную силу весом одного угла машины (42% от общей массы),
// чтобы домкрат физически не мог перевернуть или подбросить автомобиль!
float maxCornerWeight = targetCarRb.mass * gravity * 0.42f;
float springForce = heightError * (targetCarRb.mass * 85f);
float damperForce = pointVelY * (targetCarRb.mass * 16f);
supportAnchorObj = new GameObject("JackPhysicsSupport");
supportAnchorObj.transform.position = contactWorld;
float upwardForce = Mathf.Clamp(springForce - damperForce, 0f, maxCornerWeight);
targetCarRb.AddForceAtPosition(Vector3.up * upwardForce, currentSillWorld, ForceMode.Force);
supportAnchorRb = supportAnchorObj.AddComponent<Rigidbody>();
supportAnchorRb.isKinematic = true;
supportAnchorRb.interpolation = RigidbodyInterpolation.Interpolate;
// Гасим паразитное раскачивание и сползание кузова
targetCarRb.angularVelocity *= 0.85f;
Vector3 horizVel = new Vector3(targetCarRb.linearVelocity.x, 0f, targetCarRb.linearVelocity.z);
targetCarRb.AddForce(-horizVel * (targetCarRb.mass * 8f), ForceMode.Force);
liftJoint = supportAnchorObj.AddComponent<ConfigurableJoint>();
liftJoint.connectedBody = targetCarRb;
liftJoint.autoConfigureConnectedAnchor = false;
liftJoint.anchor = Vector3.zero;
liftJoint.connectedAnchor = targetCarRb.transform.InverseTransformPoint(contactWorld);
// Разрешаем свободный наклон кузова, но плавно и жестко держим высоту точки опоры
liftJoint.xMotion = ConfigurableJointMotion.Free;
liftJoint.yMotion = ConfigurableJointMotion.Free;
liftJoint.zMotion = ConfigurableJointMotion.Free;
liftJoint.angularXMotion = ConfigurableJointMotion.Free;
liftJoint.angularYMotion = ConfigurableJointMotion.Free;
liftJoint.angularZMotion = ConfigurableJointMotion.Free;
JointDrive verticalDrive = new JointDrive
{
positionSpring = targetCarRb.mass * 180f,
positionDamper = targetCarRb.mass * 28f,
maximumForce = targetCarRb.mass * 60f
};
JointDrive horizontalDrive = new JointDrive
{
positionSpring = targetCarRb.mass * 25f,
positionDamper = targetCarRb.mass * 8f,
maximumForce = targetCarRb.mass * 20f
};
liftJoint.yDrive = verticalDrive;
liftJoint.xDrive = horizontalDrive;
liftJoint.zDrive = horizontalDrive;
}
private void DestroyLiftJoint()
{
if (supportAnchorObj != null)
Destroy(supportAnchorObj);
supportAnchorObj = null;
supportAnchorRb = null;
liftJoint = null;
}
private bool CanLowerSafely()
@@ -252,25 +307,22 @@ public class CarJack : MonoBehaviour, IInteractable
if (currentState == JackState.PlacedUnderCar)
{
int percent = Mathf.RoundToInt(liftProgress * 100f);
if (!CanLowerSafely())
return $"Домкрат поднят ({percent}%)\n<color=yellow>Установите колесо и закрутите болты перед спуском!</color>";
return $"Домкрат поднят ({percent}%)\n<color=yellow>Наденьте колесо и закрутите болты перед спуском!</color>";
if (liftProgress <= 0.01f)
return "[Удерж. E] Поднимать авто | [G] Забрать домкрат";
return $"Домкрат ({percent}%)\n[Удерж. E] Поднять | [Удерж. R] Опустить";
}
return string.Empty;
}
public string GetPlacementPrompt()
{
if (canPlaceUnderCar)
return "[E / ЛКМ] Установить домкрат под порог | [G] Выбросить";
return "Наведите на колесо или под порог авто | [G] Выбросить домкрат";
return "[E / ЛКМ] Поставить домкрат под порог | [G] Выбросить";
return "Наведите на колесо или порог авто | [G] Выбросить домкрат";
}
public void Interact(GameObject interactor)
@@ -283,17 +335,17 @@ public class CarJack : MonoBehaviour, IInteractable
Camera cam = interactor.GetComponentInChildren<Camera>();
Transform camTr = cam != null ? cam.transform : FindAnyObjectByType<PlayerInteractor>()?.transform;
if (camTr != null)
{
PickUpToHand(camTr, interactor.transform.root);
}
}
}
private void PickUpToHand(Transform camTransform, Transform rootTransform)
{
if (camTransform == null) return;
if (ActiveJackInHand != null && ActiveJackInHand != this) return;
DestroyLiftJoint();
holderCamera = camTransform;
playerRoot = rootTransform;
ActiveJackInHand = this;
@@ -303,14 +355,13 @@ public class CarJack : MonoBehaviour, IInteractable
targetCarRb = null;
targetWheelPart = null;
targetWheelCollider = null;
allCarWheels = null;
liftProgress = 0f;
if (jackRb != null) Destroy(jackRb);
mainCollider.enabled = false;
transform.SetParent(holderCamera);
transform.localScale = originalLocalScale;
transform.localScale = originalRootScale;
transform.localPosition = inHandOffset;
transform.localRotation = Quaternion.Euler(inHandRotation);
UpdateJackPose();
@@ -364,19 +415,18 @@ public class CarJack : MonoBehaviour, IInteractable
if (carRb != null)
{
Transform carTr = carRb.transform;
Vector3 localWheel = carTr.InverseTransformPoint(closestWheel.transform.position);
float zOffset = -Mathf.Sign(localWheel.z) * 0.48f;
float sideSign = Mathf.Sign(localWheel.x);
if (sideSign == 0f) sideSign = 1f;
Vector3 localSill = new Vector3(localWheel.x * 0.92f, localWheel.y, localWheel.z + zOffset);
Vector3 localSill = new Vector3(localWheel.x * 0.94f, localWheel.y, localWheel.z + zOffset);
Vector3 worldSill = carTr.TransformPoint(localSill);
Vector3 groundPoint = worldSill;
groundPoint.y = closestWheel.transform.position.y - closestWheel.radius;
RaycastHit[] groundHits = Physics.RaycastAll(worldSill + Vector3.up * 0.5f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
RaycastHit[] groundHits = Physics.RaycastAll(worldSill + Vector3.up * 0.4f, Vector3.down, 2.0f, ~0, QueryTriggerInteraction.Ignore);
foreach (var gh in groundHits)
{
if (gh.collider.transform.IsChildOf(carTr)) continue;
@@ -416,9 +466,7 @@ public class CarJack : MonoBehaviour, IInteractable
private CarPart FindMatchingWheelPart(Transform carRoot, string wheelName)
{
foreach (CarPart p in carRoot.GetComponentsInChildren<CarPart>(true))
{
if (p.name == wheelName) return p;
}
return null;
}
@@ -430,77 +478,96 @@ public class CarJack : MonoBehaviour, IInteractable
SetGhostVisual(false);
transform.SetParent(null);
transform.localScale = originalLocalScale;
transform.position = previewWorldPos;
transform.rotation = previewWorldRot;
// ВАЖНО: делаем коллайдер ТРИГГЕРОМ, чтобы он не подбрасывал кузов машины!
mainCollider.enabled = true;
mainCollider.isTrigger = true;
targetCarRb = previewCarRb;
targetWheelPart = previewWheelPart;
targetWheelCollider = previewWheelCol;
allCarWheels = targetCarRb.GetComponentsInChildren<WheelCollider>(true);
// Находим точную высоту нижней кромки порога прямо над домкратом
float sillY = FindCarBottomYAboveJack(targetCarRb.transform);
initialSillWorldY = sillY;
float sillClearance = 0.16f;
if (targetWheelCollider != null)
{
float wheelBottomY = previewWorldPos.y;
float hubY = targetWheelCollider.transform.position.y;
sillClearance = Mathf.Clamp((hubY - wheelBottomY) * 0.58f, 0.12f, 0.22f);
}
Vector3 contactWorld = new Vector3(transform.position.x, sillY, transform.position.z);
carLocalLiftPoint = targetCarRb.transform.InverseTransformPoint(contactWorld);
initialSillWorldY = transform.position.y + sillClearance;
float maxTargetJackHeight = sillClearance + carLiftHeight;
float requiredScaleY = maxTargetJackHeight / Mathf.Max(0.1f, modelFullHeight);
transform.localScale = new Vector3(originalRootScale.x, requiredScaleY, originalRootScale.z);
Vector3 contactWorld = new Vector3(transform.position.x, initialSillWorldY, transform.position.z);
CreateLiftJoint(contactWorld);
liftProgress = 0f;
UpdateJackPose();
}
private float FindCarBottomYAboveJack(Transform carTr)
{
// Стреляем лучом снизу вверх из земли в порог машины, чтобы узнать точную высоту днища
Vector3 origin = transform.position + Vector3.down * 0.05f;
RaycastHit[] upHits = Physics.RaycastAll(origin, Vector3.up, 1.0f, ~0, QueryTriggerInteraction.Ignore);
float lowestCarY = float.MaxValue;
foreach (var h in upHits)
{
if (h.collider.transform.IsChildOf(carTr) && !(h.collider is WheelCollider))
{
if (h.point.y < lowestCarY)
lowestCarY = h.point.y;
}
}
if (lowestCarY < float.MaxValue)
return lowestCarY;
// Если на пороге нет коллайдера — берем уровень ступицы колеса минус 6 см
if (targetWheelCollider != null)
return targetWheelCollider.transform.position.y - 0.06f;
return transform.position.y + 0.16f;
}
private void DropToFloor()
{
DestroyLiftJoint();
ActiveJackInHand = null;
currentState = JackState.OnFloor;
stateChangeFrame = Time.frameCount;
SetGhostVisual(false);
transform.SetParent(null);
transform.localScale = originalLocalScale;
transform.localScale = originalRootScale;
if (holderCamera != null)
{
transform.position = holderCamera.position + holderCamera.forward * 1.2f;
// 1. Вычисляем горизонтальную точку перед игроком (независимо от наклона камеры вниз)
Vector3 flatForward = Vector3.ProjectOnPlane(holderCamera.forward, Vector3.up).normalized;
if (flatForward.sqrMagnitude < 0.01f) flatForward = holderCamera.up;
Vector3 dropPos = holderCamera.position + flatForward * 1.1f;
// 2. Ищем уровень пола лучом сверху вниз, чтобы НИКОГДА не заспавнить домкрат под асфальтом
Vector3 rayStart = new Vector3(dropPos.x, holderCamera.position.y + 0.5f, dropPos.z);
RaycastHit[] hits = Physics.RaycastAll(rayStart, Vector3.down, 5.0f, ~0, QueryTriggerInteraction.Ignore);
float highestGroundY = float.MinValue;
foreach (var h in hits)
{
if (h.collider.transform.IsChildOf(transform)) continue;
if (playerRoot != null && h.collider.transform.IsChildOf(playerRoot)) continue;
if (h.point.y > highestGroundY)
highestGroundY = h.point.y;
}
if (highestGroundY > float.MinValue)
{
// Ставим на 8 см выше найденного асфальта, чтобы домкрат мягко упал на него сверху
dropPos.y = highestGroundY + 0.08f;
}
else
{
dropPos.y = holderCamera.position.y - 0.3f;
}
transform.position = dropPos;
transform.rotation = Quaternion.Euler(0f, holderCamera.eulerAngles.y, 0f);
}
// На полу вне машины коллайдер твердый, чтобы домкрат лежал на асфальте
mainCollider.enabled = true;
mainCollider.isTrigger = false;
jackRb = gameObject.AddComponent<Rigidbody>();
if (jackRb == null) jackRb = gameObject.GetComponent<Rigidbody>();
if (jackRb == null) jackRb = gameObject.AddComponent<Rigidbody>();
jackRb.mass = 8f;
jackRb.interpolation = RigidbodyInterpolation.Interpolate;
// Continuous защищает от пролета сквозь тонкий MeshCollider дороги
jackRb.collisionDetectionMode = CollisionDetectionMode.Continuous;
jackRb.linearVelocity = Vector3.zero;
jackRb.angularVelocity = Vector3.zero;
}
private void SetGhostVisual(bool isGhost)
@@ -511,10 +578,7 @@ public class CarJack : MonoBehaviour, IInteractable
for (int i = 0; i < renderers.Length; i++)
{
if (renderers[i] == null) continue;
if (isGhost && ghostMaterial != null)
renderers[i].sharedMaterial = ghostMaterial;
else
renderers[i].sharedMaterial = originalMaterials[i];
renderers[i].sharedMaterial = (isGhost && ghostMaterial != null) ? ghostMaterial : originalMaterials[i];
}
}
@@ -524,59 +588,34 @@ public class CarJack : MonoBehaviour, IInteractable
liftProgress = Mathf.Clamp01(liftProgress + delta);
if (Mathf.Abs(liftProgress - prev) > 0.0001f)
{
screwSpinAngle += delta * 2160f;
UpdateJackPose();
}
}
private void UpdateJackPose()
{
float fold = (1f - liftProgress) * maxFoldAngle;
float heightRatio = Mathf.Lerp(0.45f, 1.0f, liftProgress);
float widthRatio = Mathf.Lerp(1.14f, 1.0f, liftProgress);
if (bottomArmL != null)
bottomArmL.localRotation = bArmL_OpenRot * Quaternion.Euler(armRotationAxis * (fold * foldSignL));
if (bottomArmR != null)
bottomArmR.localRotation = bArmR_OpenRot * Quaternion.Euler(armRotationAxis * (fold * foldSignR));
if (diamondPivot != null)
diamondPivot.localScale = new Vector3(widthRatio, heightRatio, widthRatio);
if (topArmL != null)
topArmL.localRotation = tArmL_OpenRot * Quaternion.Euler(armRotationAxis * (-fold * foldSignL * 2f));
if (topArmR != null)
topArmR.localRotation = tArmR_OpenRot * Quaternion.Euler(armRotationAxis * (-fold * foldSignR * 2f));
if (screw != null && topArmL != null && topArmR != null)
if (topPlate != null)
{
Vector3 sPos = screw.position;
sPos.y = (topArmL.position.y + topArmR.position.y) * 0.5f;
screw.position = sPos;
screw.localRotation = Quaternion.Euler(screwSpinAxis * screwSpinAngle);
topPlate.localPosition = new Vector3(
topPlateInitLocalPos.x,
topPlateInitLocalPos.y * heightRatio,
topPlateInitLocalPos.z
);
}
if (topPlate != null && topArmL != null)
if (screw != null)
{
float baseY = transform.position.y;
float jointOffset = topArmL.position.y - baseY;
Vector3 pPos = topPlate.position;
// Если домкрат стоит под машиной, привязываем высоту площадки к реальному порогу,
// чтобы площадка вплотную упиралась в днище без зазора и левитации!
if (currentState == JackState.PlacedUnderCar && targetCarRb != null)
{
float foldedY = initialSillWorldY - 0.04f;
float contactY = initialSillWorldY;
float maxLiftedY = initialSillWorldY + carLiftHeight;
if (liftProgress <= 0.25f)
pPos.y = Mathf.Lerp(foldedY, contactY, liftProgress / 0.25f);
else
pPos.y = Mathf.Lerp(contactY, maxLiftedY, (liftProgress - 0.25f) / 0.75f);
}
else
{
pPos.y = baseY + jointOffset * 2f;
}
topPlate.position = pPos;
screw.localPosition = new Vector3(
screwInitLocalPos.x,
screwInitLocalPos.y * heightRatio,
screwInitLocalPos.z
);
screw.localRotation = screwInitLocalRot;
}
}
}
+27 -52
View File
@@ -4,9 +4,8 @@ using UnityEngine;
public class WheelBolt : MonoBehaviour, IInteractable
{
[Header("Настройки вылета и скорости")]
[Tooltip("На сколько метров болт выдвигается наружу при откручивании")]
[SerializeField] private float pullOutDistance = 0.06f;
[SerializeField] private float workDuration = 0.6f; // Время на 1 болт (сек)
[SerializeField] private float workDuration = 0.5f;
private CarPart parentWheel;
private MeshRenderer meshRenderer;
@@ -17,19 +16,20 @@ public class WheelBolt : MonoBehaviour, IInteractable
private Vector3 tightenedLocalPos;
private Quaternion tightenedLocalRot;
private Vector3 baseLocalScale;
// Реальный геометрический центр меша болта и направление наружу (на игрока)
private Vector3 localMeshCenter;
private Vector3 boltCenterInParent;
private Vector3 parentOutwardDir;
// 1 = полностью закручен, 0 = полностью выкручен
private float tightness = 1f;
private bool isTightened = true;
private bool isHoveredThisFrame = false;
private bool waitForRelease = false;
public bool IsTightened => isTightened;
public bool IsAvailableForAim => parentWheel == null || parentWheel.State == PartState.Installed;
public Vector3 WorldBoltCenter => transform.TransformPoint(localMeshCenter);
private void Awake()
{
@@ -40,23 +40,17 @@ public class WheelBolt : MonoBehaviour, IInteractable
tightenedLocalPos = transform.localPosition;
tightenedLocalRot = transform.localRotation;
baseLocalScale = transform.localScale;
// 1. Находим реальный центр геометрии болта (даже если пивот сбит в центр колеса)
MeshFilter mf = GetComponent<MeshFilter>();
if (mf != null && mf.sharedMesh != null)
{
localMeshCenter = mf.sharedMesh.bounds.center;
}
// Привязываем сферу коллайдера строго к геометрии самого болта
boltCollider.isTrigger = true;
boltCollider.center = localMeshCenter;
boltCollider.radius = 0.065f;
boltCollider.radius = 0.045f;
// Запоминаем позицию центра болта в координатах родителя (колеса)
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
// 2. Автоматически вычисляем вектор "наружу от машины" (на игрока)
boltCenterInParent = tightenedLocalPos + tightenedLocalRot * Vector3.Scale(localMeshCenter, baseLocalScale);
CalculateOutwardDirection();
if (meshRenderer != null)
@@ -69,8 +63,6 @@ public class WheelBolt : MonoBehaviour, IInteractable
private void CalculateOutwardDirection()
{
Vector3 worldBoltPos = transform.TransformPoint(localMeshCenter);
// Находим корень автомобиля, чтобы понять, с левой или с правой стороны стоит колесо
VehicleInteraction car = GetComponentInParent<VehicleInteraction>();
Transform carRoot = car != null ? car.transform : transform.root;
@@ -78,19 +70,14 @@ public class WheelBolt : MonoBehaviour, IInteractable
float sideSign = Mathf.Sign(Vector3.Dot(fromCarToBolt, carRoot.right));
if (sideSign == 0f) sideSign = 1f;
// Вектор наружу в мировых координатах (влево для левых колес, вправо для правых)
Vector3 worldOutDir = carRoot.right * sideSign;
// Переводим в систему координат родителя болта (Wheel_FL / Wheel_FR)
if (transform.parent != null)
parentOutwardDir = transform.parent.InverseTransformDirection(worldOutDir).normalized;
else
parentOutwardDir = Vector3.right * sideSign;
parentOutwardDir = transform.parent != null
? transform.parent.InverseTransformDirection(worldOutDir).normalized
: Vector3.right * sideSign;
}
private void LateUpdate()
{
// Если само колесо снято с машины — болты полностью скрыты
if (parentWheel != null && parentWheel.State != PartState.Installed)
{
if (meshRenderer != null && meshRenderer.enabled) meshRenderer.enabled = false;
@@ -108,31 +95,29 @@ public class WheelBolt : MonoBehaviour, IInteractable
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
bool isAnimating = tightness > 0.01f && tightness < 0.99f;
// Визуально увеличиваем КОНКРЕТНЫЙ выбранный болт под прицелом, чтобы игрок видел, куда навелся
float scaleMult = (isHoveredThisFrame && hasWrench) ? 1.25f : 1.0f;
UpdateBoltTransform(scaleMult);
if (meshRenderer != null)
{
if (isTightened || isAnimating)
{
// Болт закручен (или сейчас крутится):
// Если в руках КЛЮЧ — подсвечиваем его материалом GhostPart, чтобы игрок видел, что крутить!
// Если ключа нет — показываем обычный металл.
meshRenderer.enabled = true;
if (hasWrench && ghostMaterial != null)
// Подсвечиваем только тот болт, на который сейчас наведен прицел!
if (isHoveredThisFrame && hasWrench && ghostMaterial != null)
meshRenderer.sharedMaterial = ghostMaterial;
else if (originalMaterial != null)
meshRenderer.sharedMaterial = originalMaterial;
}
else
{
// Болт выкручен (исчез):
// Показываем силуэт ТОЛЬКО когда игрок с ключом наводится на отверстие для закрутки
bool showGhostHole = hasWrench && isHoveredThisFrame;
meshRenderer.enabled = showGhostHole;
if (showGhostHole && ghostMaterial != null)
{
// Выкрученный болт: показываем силуэт отверстия при взятом ключе
meshRenderer.enabled = hasWrench && isHoveredThisFrame;
if (meshRenderer.enabled && ghostMaterial != null)
meshRenderer.sharedMaterial = ghostMaterial;
}
}
}
isHoveredThisFrame = false;
}
@@ -147,27 +132,23 @@ public class WheelBolt : MonoBehaviour, IInteractable
}
bool hasWrench = toolManager != null && toolManager.currentTool == ToolType.Wrench;
if (!hasWrench)
{
waitForRelease = false;
return isTightened
? "Болт (Возьмите баллонный ключ [Tab])"
: "Место под болт (Возьмите ключ [Tab])";
? "Колесный болт (Возьмите баллонный ключ [Tab])"
: "Отверстие под болт (Возьмите ключ [Tab])";
}
bool isHoldingKey = Input.GetMouseButton(0) || Input.GetKey(KeyCode.E);
// Снимаем блокировку только когда игрок отпустил кнопку мыши/клавиатуры
if (!isHoldingKey)
{
waitForRelease = false;
tightness = isTightened ? 1f : 0f;
UpdateBoltTransform();
}
else if (!waitForRelease)
{
// Крутим болт, только если действие не заблокировано после прошлого завершения
ProcessWrench(Time.deltaTime);
}
@@ -186,43 +167,37 @@ public class WheelBolt : MonoBehaviour, IInteractable
if (isTightened)
{
tightness -= step;
UpdateBoltTransform();
if (tightness <= 0f)
{
tightness = 0f;
isTightened = false;
waitForRelease = true; // Ждем отпускания кнопки, чтобы не закрутить обратно!
waitForRelease = true;
}
}
else
{
tightness += step;
UpdateBoltTransform();
if (tightness >= 1f)
{
tightness = 1f;
isTightened = true;
waitForRelease = true; // Ждем отпускания кнопки, чтобы не открутить обратно!
UpdateBoltTransform();
waitForRelease = true;
}
}
}
private void UpdateBoltTransform()
private void UpdateBoltTransform(float scaleMultiplier = 1f)
{
float outFactor = 1f - Mathf.Clamp01(tightness);
Vector3 currentScale = baseLocalScale * scaleMultiplier;
// Вращаем болт вокруг оси вылета (2 полных оборота = 720 градусов)
Quaternion spinRotation = Quaternion.AngleAxis(outFactor * 720f, parentOutwardDir);
Quaternion newLocalRot = spinRotation * tightenedLocalRot;
// Компенсируем смещенный пивот, чтобы болт крутился строго на месте вокруг своего центра,
// и сдвигаем его наружу к игроку по вектору parentOutwardDir
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, transform.localScale);
Vector3 rotatedCenterOffset = newLocalRot * Vector3.Scale(localMeshCenter, currentScale);
Vector3 pullOutOffset = parentOutwardDir * (pullOutDistance * outFactor);
transform.localScale = currentScale;
transform.localRotation = newLocalRot;
transform.localPosition = boltCenterInParent - rotatedCenterOffset + pullOutOffset;
}
@@ -3,10 +3,14 @@ using UnityEngine;
public class CarConditionGenerator : MonoBehaviour
{
[Header("Настройки спавна")]
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f; // Шанс появления ржавчины
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.7f;
[SerializeField] private float minRustAmount = 0.2f;
[SerializeField] private float maxRustAmount = 0.85f;
[SerializeField] private Color baseCarColor = Color.gray;
[SerializeField] private float maxRustAmount = 0.75f;
[Header("Цвет кузова")]
[Tooltip("Включите, только если хотите принудительно перекрасить машину при старте")]
[SerializeField] private bool overrideMaterialColor = false;
[SerializeField] private Color baseCarColor = Color.blue;
private void Start()
{
@@ -16,29 +20,46 @@ public class CarConditionGenerator : MonoBehaviour
[ContextMenu("Сгенерировать состояние")]
public void GenerateCondition()
{
// 1. Обрабатываем все съемные детали (CarPart)
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
foreach (CarPart part in allParts)
{
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
// 1. Базовый цвет кузова
if (overrideMaterialColor)
visuals.SetPaintColor(baseCarColor);
// 2. Пластиковые детали (бампер) не ржавеют
if (part.Data != null && !part.Data.canRust)
{
visuals.SetDamage(0f);
continue;
}
// 3. Для металла - случайное начальное повреждение
float damage = Random.value < rustProbability
? Random.Range(minRustAmount, maxRustAmount)
: 0f;
visuals.SetDamage(damage);
}
// 2. Обрабатываем основной кузов (body), на котором нет CarPart, чтобы он не оставался ржавым из материала
int rustProp = Shader.PropertyToID("_RustAmount");
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
if (r.GetComponentInParent<CarPart>(true) != null) continue;
foreach (Material m in r.sharedMaterials)
{
if (m != null && m.HasProperty(rustProp))
{
CarPartVisuals bodyVis = r.GetComponent<CarPartVisuals>();
if (bodyVis == null) bodyVis = r.gameObject.AddComponent<CarPartVisuals>();
if (overrideMaterialColor) bodyVis.SetPaintColor(baseCarColor);
bodyVis.SetDamage(Random.value < rustProbability ? Random.Range(minRustAmount, maxRustAmount) : 0f);
break;
}
}
}
}
}
+16 -48
View File
@@ -1,24 +1,11 @@
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Стадии ремонта кузовной детали. Вычисляются из значений прогресса, отдельно хранить не нужно.
/// </summary>
public enum RepairStage
{
Healthy, // деталь целая, ржавчины нет
Rusted, // есть ржавчина - нужна зачистка
Cleaned, // ржавчина счищена, голый металл - нужна шпаклёвка
Puttied, // зашпаклёвано - нужна шлифовка
Sanded, // отшлифовано - нужна покраска
Repaired // покрашено, ремонт завершён
Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired
}
/// <summary>
/// Состояние внешнего вида детали и стадии ремонта. Значения передаются в шейдер CarPaint_Rust
/// через MaterialPropertyBlock, только в те слоты материалов, где этот шейдер есть
/// (стёкла, фары и т.п. на той же детали не затрагиваются).
/// </summary>
[DisallowMultipleComponent]
public class CarPartVisuals : MonoBehaviour
{
@@ -29,13 +16,12 @@ public class CarPartVisuals : MonoBehaviour
private static readonly int SandProp = Shader.PropertyToID("_SandProgress");
private static readonly int PaintProp = Shader.PropertyToID("_PaintProgress");
// Порог, после которого стадия считается завершённой (и значение "защёлкивается" до 100%)
private const float DoneThreshold = 0.98f;
private const float RustCleanThreshold = 0.02f;
[Header("Состояние (можно крутить в инспекторе во время Play)")]
[Range(0f, 1f)] [SerializeField] private float rustInitial; // сколько детали было поражено
[Range(0f, 1f)] [SerializeField] private float rustCurrent; // сколько ржавчины осталось
[Header("Состояние детали")]
[Range(0f, 1f)] [SerializeField] private float rustInitial;
[Range(0f, 1f)] [SerializeField] private float rustCurrent;
[Range(0f, 1f)] [SerializeField] private float putty;
[Range(0f, 1f)] [SerializeField] private float sanding;
[Range(0f, 1f)] [SerializeField] private float paint;
@@ -50,6 +36,7 @@ public class CarPartVisuals : MonoBehaviour
private readonly List<Slot> slots = new List<Slot>();
private MaterialPropertyBlock block;
private bool initialized;
private bool colorInitialized;
public float CurrentRust => rustCurrent;
public float InitialRust => rustInitial;
@@ -68,7 +55,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
/// <summary>Прогресс текущей стадии 0..1 (для подсказок и UI).</summary>
public float StageProgress
{
get
@@ -84,8 +70,6 @@ public class CarPartVisuals : MonoBehaviour
}
}
// ---------- Инициализация ----------
private void EnsureInit()
{
if (initialized) return;
@@ -96,35 +80,33 @@ public class CarPartVisuals : MonoBehaviour
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
{
// Не трогаем рендереры вложенных деталей (например, зеркало внутри двери)
if (owner != null && r.GetComponentInParent<CarPart>(true) != owner) continue;
Material[] mats = r.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i] != null && mats[i].HasProperty(RustAmountProp))
{
// Автоматически запоминаем родной цвет машины из материала (например, синий!)
if (!colorInitialized && mats[i].HasProperty(BaseColorProp))
{
paintColor = mats[i].GetColor(BaseColorProp);
colorInitialized = true;
}
slots.Add(new Slot { renderer = r, materialIndex = i });
}
}
if (slots.Count == 0)
{
Debug.LogWarning($"[{name}] Нет материалов с шейдером CarPaint_Rust (свойство _RustAmount). " +
"Ржавчина и ремонт на этой детали не будут видны.", this);
}
}
private void OnValidate()
{
// Позволяет двигать слайдеры в инспекторе и сразу видеть результат
if (Application.isPlaying && initialized) Apply();
}
// ---------- Установка состояния ----------
/// <summary>Задать начальное повреждение детали (0 = целая). Сбрасывает все стадии ремонта.</summary>
public void SetDamage(float amount)
{
EnsureInit();
amount = Mathf.Clamp01(amount);
if (amount <= 0.001f) amount = 0f;
@@ -136,21 +118,17 @@ public class CarPartVisuals : MonoBehaviour
Apply();
}
/// <summary>Задать цвет краски без проверок (для генератора состояния).</summary>
public void SetPaintColor(Color newColor)
{
EnsureInit();
paintColor = newColor;
colorInitialized = true;
Apply();
}
// ---------- Действия инструментов ----------
// amount01 - доля полной работы за этот кадр (deltaTime / время полной обработки).
// Возвращают false, если инструмент сейчас не подходит этой стадии.
public bool CleanRust(float amount01)
{
if (Stage != RepairStage.Rusted) return false;
rustCurrent -= rustInitial * amount01;
if (rustCurrent <= RustCleanThreshold) rustCurrent = 0f;
Apply();
@@ -160,7 +138,6 @@ public class CarPartVisuals : MonoBehaviour
public bool ApplyPutty(float amount01)
{
if (Stage != RepairStage.Cleaned) return false;
putty = Mathf.Min(1f, putty + amount01);
if (putty >= DoneThreshold) putty = 1f;
Apply();
@@ -170,7 +147,6 @@ public class CarPartVisuals : MonoBehaviour
public bool Sand(float amount01)
{
if (Stage != RepairStage.Puttied) return false;
sanding = Mathf.Min(1f, sanding + amount01);
if (sanding >= DoneThreshold) sanding = 1f;
Apply();
@@ -180,34 +156,26 @@ public class CarPartVisuals : MonoBehaviour
public bool PaintRepair(float amount01)
{
if (Stage != RepairStage.Sanded) return false;
paint = Mathf.Min(1f, paint + amount01);
if (paint >= DoneThreshold) paint = 1f;
Apply();
return true;
}
/// <summary>Перекраска целой или уже отремонтированной детали в другой цвет.</summary>
public bool Recolor(Color newColor)
{
RepairStage s = Stage;
if (s != RepairStage.Healthy && s != RepairStage.Repaired) return false;
paintColor = newColor;
Apply();
SetPaintColor(newColor);
return true;
}
// ---------- Передача в шейдер ----------
private void Apply()
{
EnsureInit();
foreach (Slot s in slots)
{
if (s.renderer == null) continue;
s.renderer.GetPropertyBlock(block, s.materialIndex);
block.SetColor(BaseColorProp, paintColor);
block.SetFloat(RustInitialProp, rustInitial);
@@ -3,7 +3,7 @@ using UnityEngine;
public class PlayerInteractor : MonoBehaviour
{
[Header("Настройки луча")]
[SerializeField] private float interactRange = 3f;
[SerializeField] private float interactRange = 3.2f;
[SerializeField] private LayerMask interactableLayer;
[Header("Клавиши управления")]
@@ -15,11 +15,12 @@ public class PlayerInteractor : MonoBehaviour
[SerializeField] private UIManager uiManager;
private CarPart lastHoveredPart;
private PlayerHands cachedHands;
private void Awake()
{
if (uiManager == null)
uiManager = FindAnyObjectByType<UIManager>();
if (uiManager == null) uiManager = FindAnyObjectByType<UIManager>();
cachedHands = FindAnyObjectByType<PlayerHands>();
}
private void OnDisable()
@@ -30,34 +31,40 @@ public class PlayerInteractor : MonoBehaviour
private void Update()
{
if (CarJack.ActiveJackInHand != null)
{
uiManager?.ShowPrompt(CarJack.ActiveJackInHand.GetPlacementPrompt());
return;
}
if (CarJack.ActiveJackInHand != null) return;
Ray ray = new Ray(transform.position, transform.forward);
GameObject playerRoot = transform.root.gameObject;
// 0. Если в руках деталь — проверяем все зоны установки по лучу (чтобы кузов не перекрывал зону колеса!)
if (cachedHands == null) cachedHands = FindAnyObjectByType<PlayerHands>();
if (cachedHands != null && cachedHands.IsHolding)
{
RaycastHit[] allHits = Physics.RaycastAll(ray, interactRange, interactableLayer, QueryTriggerInteraction.Collide);
foreach (var h in allHits)
{
CarPartMountZone zone = h.collider.GetComponentInParent<CarPartMountZone>();
if (zone != null)
{
ResetProgressTargets();
string zPrompt = zone.GetPrompt();
if (!string.IsNullOrEmpty(zPrompt))
uiManager?.ShowPrompt(zPrompt);
else
uiManager?.HidePrompt();
return;
}
}
}
if (Physics.Raycast(ray, out RaycastHit hit, interactRange, interactableLayer, QueryTriggerInteraction.Collide))
{
GameObject playerRoot = transform.root.gameObject;
// 1. ПРИОРИТЕТ БОЛТАМ: проверяем, не целимся ли мы в колесный болт (даже сквозь коллайдер шины)
WheelBolt bolt = hit.collider.GetComponent<WheelBolt>();
if (bolt == null)
{
Collider[] nearCols = Physics.OverlapSphere(hit.point, 0.06f, interactableLayer, QueryTriggerInteraction.Collide);
foreach (var c in nearCols)
{
bolt = c.GetComponent<WheelBolt>();
if (bolt != null) break;
}
}
if (bolt != null)
// 1. ТОЧНЫЙ ПОИСК БЛИЖАЙШЕГО К ПРИЦЕЛУ БОЛТА
WheelBolt bestBolt = FindClosestBoltToRay(ray, hit.point);
if (bestBolt != null)
{
ResetProgressTargets();
string boltPrompt = bolt.GetPrompt();
string boltPrompt = bestBolt.GetPrompt();
if (!string.IsNullOrEmpty(boltPrompt))
uiManager?.ShowPrompt(boltPrompt);
else
@@ -65,7 +72,28 @@ public class PlayerInteractor : MonoBehaviour
return;
}
// 2. Обычные объекты, детали и авто
// 2. ПРИОРИТЕТ ДОМКРАТУ ПОД ПОРОГОМ
CarJack jack = hit.collider.GetComponentInParent<CarJack>();
if (jack == null)
{
Collider[] nearJackCols = Physics.OverlapSphere(hit.point, 0.22f, interactableLayer, QueryTriggerInteraction.Collide);
foreach (var c in nearJackCols)
{
jack = c.GetComponentInParent<CarJack>();
if (jack != null) break;
}
}
if (jack != null)
{
ResetProgressTargets();
uiManager?.ShowPrompt(jack.GetPrompt());
if (Input.GetKeyDown(primaryKey))
jack.Interact(playerRoot);
return;
}
// 3. ОБЫЧНЫЕ ДЕТАЛИ И АВТОМОБИЛЬ
IInteractable interactable = hit.collider.GetComponentInParent<IInteractable>();
VehicleInteraction vehicle = hit.collider.GetComponentInParent<VehicleInteraction>();
CarPart part = hit.collider.GetComponentInParent<CarPart>();
@@ -79,21 +107,13 @@ public class PlayerInteractor : MonoBehaviour
if (interactable != null || vehicle != null)
{
// Посадка в авто (F)
if (Input.GetKeyDown(enterVehicleKey) && vehicle != null)
{
vehicle.Interact(playerRoot);
return;
}
// Зона обратной установки детали (обрабатывается внутри CarPartMountZone)
if (mountZone != null)
{
if (Input.GetKeyDown(primaryKey))
mountZone.Interact(playerRoot);
}
// Работа с деталью (снятие / открытие / подбор с земли)
else if (part != null)
if (mountZone == null && part != null)
{
if (part.State == PartState.Dropped)
{
@@ -103,7 +123,6 @@ public class PlayerInteractor : MonoBehaviour
else if (part.State == PartState.Installed)
{
bool hasAnimator = part.GetComponent<CarPartAnimator>() != null;
if (hasAnimator)
{
if (Input.GetKeyDown(primaryKey))
@@ -123,7 +142,7 @@ public class PlayerInteractor : MonoBehaviour
}
}
}
else if (interactable != null && Input.GetKeyDown(primaryKey))
else if (mountZone == null && interactable != null && Input.GetKeyDown(primaryKey))
{
interactable.Interact(playerRoot);
}
@@ -142,6 +161,29 @@ public class PlayerInteractor : MonoBehaviour
uiManager?.HidePrompt();
}
private WheelBolt FindClosestBoltToRay(Ray ray, Vector3 hitPoint)
{
Collider[] cols = Physics.OverlapSphere(hitPoint, 0.08f, interactableLayer, QueryTriggerInteraction.Collide);
WheelBolt closest = null;
float minRayDist = 0.045f; // Максимальное отклонение от точки прицела (4.5 см)
foreach (var c in cols)
{
WheelBolt b = c.GetComponent<WheelBolt>();
if (b == null || !b.IsAvailableForAim) continue;
// Считаем расстояние от центра конкретного болта до линии взгляда игрока
Vector3 boltPos = b.WorldBoltCenter;
float distToRay = Vector3.Cross(ray.direction, boltPos - ray.origin).magnitude;
if (distToRay < minRayDist)
{
minRayDist = distToRay;
closest = b;
}
}
return closest;
}
private string BuildPrompt(VehicleInteraction vehicle, IInteractable interactable)
{
string partPrompt = (interactable != null && !(interactable is VehicleInteraction))
+221 -55
View File
@@ -1,56 +1,209 @@
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
// Порядок важен: он совпадает с порядком секторов в ToolRadialMenu (индекс = номер сектора)
public enum ToolType
{
Hands, RustCleaner, Putty, Sander, SprayCan, Wrench
}
public class PlayerToolManager : MonoBehaviour
{
[Header("Инструмент")]
[Serializable]
public struct ToolVisualSlot
{
public ToolType toolType;
[Tooltip("Перетащите сюда префаб или объект 3D-модели инструмента")]
public GameObject toolModelOrPrefab;
public Vector3 positionOffset;
public Vector3 rotationOffset;
}
[Header("Текущий инструмент")]
public ToolType currentTool = ToolType.Hands;
[Header("3D-модели инструментов в руках")]
[SerializeField] private ToolVisualSlot[] toolModelsInHand;
[SerializeField] private Vector3 handAnchorLocalPos = new Vector3(0.32f, -0.26f, 0.55f);
[Header("Луч инструмента")]
[SerializeField] private float toolRange = 2.5f;
[SerializeField] private float toolRange = 2.8f;
[SerializeField] private LayerMask interactableLayer;
[Header("Время полной обработки детали, сек")]
[SerializeField] private float cleanTime = 5f;
[SerializeField] private float puttyTime = 3f;
[SerializeField] private float sandTime = 4f;
[SerializeField] private float paintTime = 3f;
[Header("Время полной обработки детали при ведении мыши, сек")]
[SerializeField] private float cleanTime = 3.5f;
[SerializeField] private float puttyTime = 2.5f;
[SerializeField] private float sandTime = 3.0f;
[SerializeField] private float paintTime = 2.5f;
[Header("Перекраска целой детали")]
[SerializeField] private Color sprayPaintColor = new Color(0.1f, 0.4f, 0.8f);
[Header("Подсказка о состоянии детали (необязательно)")]
[Tooltip("Если не задан - текст рисуется простым OnGUI по центру экрана")]
[Header("Отдельный текст статуса (оставьте None для авто-вывода)")]
[SerializeField] private TextMeshProUGUI statusText;
private Camera playerCam;
private Transform toolHandAnchor;
private readonly Dictionary<ToolType, GameObject> spawnedTools = new Dictionary<ToolType, GameObject>();
private GameObject activeToolObj;
private string status = "";
private GUIStyle guiStyle;
private Vector3 lastHitPoint;
private bool hadHitLastFrame;
private void Awake()
{
playerCam = GetComponentInChildren<Camera>();
if (playerCam == null) playerCam = Camera.main;
InitializeHandTools();
UpdateToolVisuals();
}
private void InitializeHandTools()
{
if (playerCam == null) return;
GameObject anchorObj = new GameObject("ToolHandAnchor");
toolHandAnchor = anchorObj.transform;
toolHandAnchor.SetParent(playerCam.transform, false);
toolHandAnchor.localPosition = handAnchorLocalPos;
toolHandAnchor.localRotation = Quaternion.identity;
// Создаем настроенные модели или процедурные меши, если слот еще пустой
foreach (ToolType type in Enum.GetValues(typeof(ToolType)))
{
if (type == ToolType.Hands) continue;
GameObject customSource = null;
Vector3 posOff = Vector3.zero;
Vector3 rotOff = Vector3.zero;
if (toolModelsInHand != null)
{
foreach (var s in toolModelsInHand)
{
if (s.toolType == type && s.toolModelOrPrefab != null)
{
customSource = s.toolModelOrPrefab;
posOff = s.positionOffset;
rotOff = s.rotationOffset;
break;
}
}
}
GameObject wrapper = new GameObject($"HandTool_{type}");
wrapper.transform.SetParent(toolHandAnchor, false);
if (customSource != null)
{
GameObject instance = !customSource.scene.IsValid()
? Instantiate(customSource, wrapper.transform)
: customSource;
instance.transform.SetParent(wrapper.transform, false);
instance.transform.localPosition = Vector3.zero;
instance.transform.localRotation = Quaternion.Euler(rotOff);
// Отключаем коллайдеры и Rigidbody на модели в руках
foreach (var col in instance.GetComponentsInChildren<Collider>(true)) col.enabled = false;
foreach (var rb in instance.GetComponentsInChildren<Rigidbody>(true)) Destroy(rb);
// Центрируем геометрию модели в точке руки (компенсируем сбитый пивот из Blender)
Renderer rend = instance.GetComponentInChildren<Renderer>();
if (rend != null)
{
Vector3 centerOffset = wrapper.transform.position - rend.bounds.center;
instance.transform.position += centerOffset;
instance.transform.localPosition += posOff;
}
}
else
{
// Если 3D-модель еще не назначена в инспекторе — собираем аккуратную 3D-модель в руке
BuildFallbackToolModel(wrapper.transform, type);
}
wrapper.SetActive(false);
spawnedTools[type] = wrapper;
}
}
private void BuildFallbackToolModel(Transform parent, ToolType type)
{
GameObject prim = GameObject.CreatePrimitive(
type == ToolType.SprayCan ? PrimitiveType.Cylinder : PrimitiveType.Cube);
Destroy(prim.GetComponent<Collider>());
prim.transform.SetParent(parent, false);
Renderer r = prim.GetComponent<Renderer>();
Material mat = new Material(Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"));
switch (type)
{
case ToolType.RustCleaner:
prim.transform.localScale = new Vector3(0.08f, 0.06f, 0.22f);
mat.color = new Color(0.85f, 0.35f, 0.1f);
break;
case ToolType.Putty:
prim.transform.localScale = new Vector3(0.12f, 0.015f, 0.20f);
prim.transform.localRotation = Quaternion.Euler(15f, 0f, 0f);
mat.color = new Color(0.75f, 0.75f, 0.78f);
break;
case ToolType.Sander:
prim.transform.localScale = new Vector3(0.11f, 0.08f, 0.18f);
mat.color = new Color(0.2f, 0.65f, 0.3f);
break;
case ToolType.SprayCan:
prim.transform.localScale = new Vector3(0.07f, 0.11f, 0.07f);
mat.color = sprayPaintColor;
break;
case ToolType.Wrench:
prim.transform.localScale = new Vector3(0.04f, 0.04f, 0.28f);
prim.transform.localRotation = Quaternion.Euler(0f, -15f, 0f);
mat.color = new Color(0.6f, 0.63f, 0.67f);
break;
}
r.sharedMaterial = mat;
}
public void SelectTool(ToolType newTool)
{
currentTool = newTool;
UpdateToolVisuals();
}
private void UpdateToolVisuals()
{
activeToolObj = null;
foreach (var kvp in spawnedTools)
{
bool active = kvp.Key == currentTool && currentTool != ToolType.Hands;
if (kvp.Value != null)
{
kvp.Value.SetActive(active);
if (active) activeToolObj = kvp.Value;
}
}
}
private void Update()
{
AnimateHandTool();
if (currentTool == ToolType.Hands || currentTool == ToolType.Wrench || Input.GetKey(KeyCode.Tab))
{
hadHitLastFrame = false;
SetStatus("");
return;
}
CarPartVisuals visuals = FindTarget();
if (visuals == null)
if (!TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint))
{
hadHitLastFrame = false;
SetStatus("");
return;
}
@@ -61,63 +214,77 @@ public class PlayerToolManager : MonoBehaviour
if (Input.GetMouseButton(0))
{
if (!UseTool(visuals)) text = HintFor(visuals.Stage);
// Проверяем, водит ли игрок инструментом по рабочей области детали
float mouseSpeed = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")).magnitude;
float worldSpeed = hadHitLastFrame ? (Vector3.Distance(hitPoint, lastHitPoint) / Mathf.Max(Time.deltaTime, 0.001f)) : 0f;
float moveMultiplier = Mathf.Clamp(mouseSpeed * 0.7f + worldSpeed * 2.0f, 0f, 2.2f);
if (moveMultiplier < 0.08f && visuals.Stage != RepairStage.Healthy && visuals.Stage != RepairStage.Repaired)
{
text += "\nВодите инструментом по детали!";
}
else if (!UseTool(visuals, moveMultiplier))
{
text = HintFor(visuals.Stage);
}
}
lastHitPoint = hitPoint;
hadHitLastFrame = true;
SetStatus(text);
}
private CarPartVisuals FindTarget()
private void AnimateHandTool()
{
if (playerCam == null) return null;
if (toolHandAnchor == null) return;
Ray ray = new Ray(playerCam.transform.position, playerCam.transform.forward);
if (activeToolObj != null && Input.GetMouseButton(0))
{
float t = Time.time;
Vector3 offset = (currentTool == ToolType.RustCleaner || currentTool == ToolType.Sander)
? new Vector3(Mathf.Sin(t * 50f), Mathf.Cos(t * 60f), 0f) * 0.01f
: new Vector3(Mathf.Sin(t * 12f) * 0.03f, Mathf.Cos(t * 8f) * 0.015f, 0f);
// Ignore: зоны монтажа - это триггеры на том же слое, луч не должен в них упираться
if (!Physics.Raycast(ray, out RaycastHit hit, toolRange, interactableLayer, QueryTriggerInteraction.Ignore))
return null;
return hit.collider.GetComponentInParent<CarPartVisuals>();
toolHandAnchor.localPosition = Vector3.Lerp(toolHandAnchor.localPosition, handAnchorLocalPos + offset, Time.deltaTime * 20f);
}
else
{
toolHandAnchor.localPosition = Vector3.Lerp(toolHandAnchor.localPosition, handAnchorLocalPos, Time.deltaTime * 12f);
}
}
private bool UseTool(CarPartVisuals visuals)
private bool TryFindTarget(out CarPartVisuals visuals, out Vector3 hitPoint)
{
float dt = Time.deltaTime;
visuals = null;
hitPoint = Vector3.zero;
if (playerCam == null) return false;
Ray ray = new Ray(playerCam.transform.position, playerCam.transform.forward);
if (!Physics.Raycast(ray, out RaycastHit hit, toolRange, interactableLayer, QueryTriggerInteraction.Ignore))
return false;
visuals = hit.collider.GetComponentInParent<CarPartVisuals>();
hitPoint = hit.point;
return visuals != null;
}
private bool UseTool(CarPartVisuals visuals, float speedMult)
{
float dt = Time.deltaTime * speedMult;
switch (currentTool)
{
case ToolType.RustCleaner:
// TODO: частицы искр / щётки и звук
return visuals.CleanRust(dt / cleanTime);
case ToolType.Putty:
return visuals.ApplyPutty(dt / puttyTime);
case ToolType.Sander:
return visuals.Sand(dt / sandTime);
case ToolType.RustCleaner: return visuals.CleanRust(dt / cleanTime);
case ToolType.Putty: return visuals.ApplyPutty(dt / puttyTime);
case ToolType.Sander: return visuals.Sand(dt / sandTime);
case ToolType.SprayCan:
// Ремонтная покраска идёт цветом детали, чтобы заплатка слилась с кузовом.
// Целую деталь баллончик перекрашивает в выбранный цвет.
if (visuals.Stage == RepairStage.Sanded) return visuals.PaintRepair(dt / paintTime);
return visuals.Recolor(sprayPaintColor);
default:
return false;
default: return false;
}
}
public void SelectTool(ToolType newTool)
{
currentTool = newTool;
}
public void SetSprayColor(Color color)
{
sprayPaintColor = color;
}
// ---------- Тексты ----------
public void SetSprayColor(Color color) => sprayPaintColor = color;
private static string StageText(RepairStage stage)
{
@@ -144,12 +311,9 @@ public class PlayerToolManager : MonoBehaviour
}
}
// ---------- Вывод ----------
private void SetStatus(string value)
{
status = value;
if (statusText != null)
{
statusText.text = value;
@@ -166,10 +330,12 @@ public class PlayerToolManager : MonoBehaviour
guiStyle = new GUIStyle(GUI.skin.label)
{
alignment = TextAnchor.MiddleCenter,
fontSize = 22
fontSize = 22,
fontStyle = FontStyle.Bold
};
guiStyle.normal.textColor = Color.white;
}
GUI.Label(new Rect(Screen.width * 0.5f - 300f, Screen.height * 0.62f, 600f, 40f), status, guiStyle);
GUI.Label(new Rect(Screen.width * 0.5f - 300f, Screen.height * 0.72f, 600f, 55f), status, guiStyle);
}
}
+90 -4
View File
@@ -1,24 +1,105 @@
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine; // Обязательно подключаем библиотеку TextMeshPro
public class UIManager : MonoBehaviour
{
[Header("UI Elements")]
[SerializeField] private TextMeshProUGUI interactText; // Ссылка на наш текст
[SerializeField] private TextMeshProUGUI interactText;
[SerializeField] private TextMeshProUGUI speedText;
[Header("Смещение подсказки от центрального прицела")]
[Tooltip("На сколько пикселей ниже точки прицела располагается текст подсказки")]
[SerializeField] private Vector2 promptOffsetFromCenter = new Vector2(0f, -120f);
[Header("Прицел (Точка по центру экрана)")]
[SerializeField] private Image crosshairDot;
[SerializeField] private Color normalDotColor = new Color(1f, 1f, 1f, 0.8f);
[SerializeField] private Color activeDotColor = new Color(0.2f, 1f, 0.35f, 1f);
[SerializeField] private float normalDotSize = 6f;
[SerializeField] private float activeDotSize = 10f;
private RectTransform dotRect;
private void Awake()
{
EnsureCrosshairExists();
PositionPromptBelowCrosshair();
}
private void Start()
{
// При старте игры подсказка должна быть скрыта
HidePrompt();
ToggleDashboard(false);
}
private void PositionPromptBelowCrosshair()
{
if (interactText == null) return;
RectTransform rt = interactText.rectTransform;
rt.anchorMin = new Vector2(0.5f, 0.5f);
rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.pivot = new Vector2(0.5f, 0.5f);
rt.anchoredPosition = promptOffsetFromCenter;
interactText.alignment = TextAlignmentOptions.Center;
interactText.raycastTarget = false;
}
private void EnsureCrosshairExists()
{
if (crosshairDot == null)
{
Canvas canvas = GetComponentInChildren<Canvas>() ?? FindAnyObjectByType<Canvas>();
if (canvas != null)
{
GameObject dotObj = new GameObject("CrosshairDot");
dotObj.transform.SetParent(canvas.transform, false);
crosshairDot = dotObj.AddComponent<Image>();
crosshairDot.raycastTarget = false;
int res = 32;
Texture2D tex = new Texture2D(res, res, TextureFormat.RGBA32, false);
Vector2 center = new Vector2(res * 0.5f, res * 0.5f);
for (int y = 0; y < res; y++)
{
for (int x = 0; x < res; x++)
{
float dist = Vector2.Distance(new Vector2(x, y), center);
float alpha = Mathf.Clamp01((res * 0.45f - dist) * 0.8f);
tex.SetPixel(x, y, new Color(1f, 1f, 1f, alpha));
}
}
tex.Apply();
crosshairDot.sprite = Sprite.Create(tex, new Rect(0, 0, res, res), new Vector2(0.5f, 0.5f));
}
}
if (crosshairDot != null)
{
dotRect = crosshairDot.GetComponent<RectTransform>();
dotRect.anchorMin = new Vector2(0.5f, 0.5f);
dotRect.anchorMax = new Vector2(0.5f, 0.5f);
dotRect.pivot = new Vector2(0.5f, 0.5f);
dotRect.anchoredPosition = Vector2.zero;
SetCrosshairHighlight(false);
}
}
public void SetCrosshairHighlight(bool isHighlighted)
{
if (crosshairDot == null || dotRect == null) return;
crosshairDot.color = isHighlighted ? activeDotColor : normalDotColor;
float s = isHighlighted ? activeDotSize : normalDotSize;
dotRect.sizeDelta = new Vector2(s, s);
}
public void ToggleDashboard(bool isActive)
{
if (speedText != null)
speedText.gameObject.SetActive(isActive);
if (crosshairDot != null)
crosshairDot.gameObject.SetActive(!isActive);
}
public void UpdateSpeed(float currentSpeed)
@@ -28,14 +109,19 @@ public class UIManager : MonoBehaviour
}
public void ShowPrompt(string message)
{
if (interactText != null)
{
interactText.text = message;
interactText.gameObject.SetActive(true);
}
SetCrosshairHighlight(true);
}
public void HidePrompt()
{
if (interactText != null)
interactText.gameObject.SetActive(false);
SetCrosshairHighlight(false);
}
}
+8 -8
View File
@@ -421,10 +421,10 @@
"m_Expanded": true,
"m_Position": {
"serializedVersion": "2",
"x": 1146.0,
"x": 1146.9998779296875,
"y": 714.9999389648438,
"width": 254.9998779296875,
"height": 286.0
"width": 255.0,
"height": 309.99993896484375
}
},
"m_Slots": [
@@ -476,11 +476,11 @@
"m_CustomColors": {
"m_SerializableColors": []
},
"m_SourceType": 0,
"m_SourceType": 1,
"m_FunctionName": "RepairSurface",
"m_FunctionSource": "8406d757d93120545ba59c440d9e5031",
"m_FunctionSourceUsePragmas": true,
"m_FunctionBody": "Enter function body here..."
"m_FunctionBody": "float e = 0.04;\nfloat3 bareMetal = float3(0.55, 0.56, 0.58);\nfloat3 puttyRaw = float3(0.62, 0.58, 0.50);\nfloat3 puttySanded = float3(0.74, 0.72, 0.68);\n\nif (RustInitial <= 0.001)\n{\n Albedo = BaseColor;\n Metallic = 0.0;\n Smoothness = PaintSmoothness;\n}\nelse\n{\n float sand = saturate(SandProgress);\n float zone = smoothstep(1.0 - RustInitial, 1.0 - RustInitial + e, N);\n\n float fillEdge = 1.0 - saturate(PuttyProgress) * (RustInitial + e);\n float puttyMask = smoothstep(fillEdge + e, fillEdge, N) * step(0.001, PuttyProgress);\n if (PuttyProgress >= 0.98) puttyMask = 1.0;\n\n float3 underColor = lerp(bareMetal, lerp(puttyRaw, puttySanded, sand), puttyMask);\n float underSmooth = lerp(0.45, lerp(0.05, 0.35, sand), puttyMask);\n float underMetal = lerp(0.8, 0.0, puttyMask);\n\n float paintEdge = (1.0 - RustInitial) + saturate(PaintProgress) * (RustInitial + e);\n float paintMask = (1.0 - smoothstep(paintEdge, paintEdge + e, N)) * step(0.001, PaintProgress);\n if (PaintProgress >= 0.98) paintMask = 1.0;\n\n float damageVisible = zone * (1.0 - paintMask);\n float rust = zone * smoothstep(1.0 - RustAmount, 1.0 - RustAmount + e, N) * step(0.001, RustAmount);\n\n float3 col = lerp(BaseColor, underColor, damageVisible);\n float sm = lerp(PaintSmoothness, underSmooth, damageVisible);\n float met = lerp(0.0, underMetal, damageVisible);\n\n Albedo = lerp(col, RustColor, rust);\n Smoothness = lerp(sm, 0.08, rust);\n Metallic = lerp(met, 0.0, rust);\n}\n"
}
{
@@ -1504,10 +1504,10 @@
"m_Expanded": true,
"m_Position": {
"serializedVersion": "2",
"x": 848.0,
"y": 1137.0,
"x": 655.9999389648438,
"y": 1179.0,
"width": 166.0,
"height": 34.0
"height": 33.9998779296875
}
},
"m_Slots": [
+24 -25
View File
@@ -1,7 +1,6 @@
#ifndef REPAIR_SURFACE_INCLUDED
#define REPAIR_SURFACE_INCLUDED
// Исправленная послойная модель реставрации кузова без артефактов на границах
void RepairSurface_float(
float N,
float3 BaseColor,
@@ -16,46 +15,50 @@ void RepairSurface_float(
out float Metallic,
out float Smoothness)
{
const float e = 0.04; // мягкость перехода
const float e = 0.04;
const float3 bareMetal = float3(0.55, 0.56, 0.58);
const float3 puttyRaw = float3(0.62, 0.58, 0.50);
const float3 puttySanded = float3(0.72, 0.70, 0.66);
const float3 puttySanded = float3(0.74, 0.72, 0.68);
// Если деталь целая (RustInitial = 0) — сразу возвращаем чистый родной цвет авто
if (RustInitial <= 0.001)
{
Albedo = BaseColor;
Metallic = 0.0;
Smoothness = PaintSmoothness;
return;
}
float sand = saturate(SandProgress);
// 1. Исходная зона повреждения детали (0..1)
float zone = smoothstep(1.0 - RustInitial, 1.0 - RustInitial + e, N) * step(0.001, RustInitial);
// 1. Исходная зона повреждения
float zone = smoothstep(1.0 - RustInitial, 1.0 - RustInitial + e, N);
// 2. Маска шпаклёвки (наносится поверх голого металла)
float fillEdge = 1.0 - PuttyProgress * (RustInitial + e);
// 2. Шпаклевка (заполняет зачищенный металл от центра к краям)
float fillEdge = 1.0 - saturate(PuttyProgress) * (RustInitial + e);
float puttyMask = smoothstep(fillEdge + e, fillEdge, N) * step(0.001, PuttyProgress);
if (PuttyProgress >= 0.99) puttyMask = 1.0;
if (PuttyProgress >= 0.98) puttyMask = 1.0;
// Свойства подложки (голый металл или шпаклёвка)
float3 underColor = lerp(bareMetal, lerp(puttyRaw, puttySanded, sand), puttyMask);
float underSmooth = lerp(0.45, lerp(0.05, 0.35, sand), puttyMask);
float underMetal = lerp(0.8, 0.0, puttyMask);
// 3. Маска нанесения новой краски (растёт от краёв зоны внутрь)
float paintEdge = (1.0 - RustInitial) + PaintProgress * (RustInitial + e);
// 3. Новая краска (закрывает зашлифованную шпаклевку без белых контуров)
float paintEdge = (1.0 - RustInitial) + saturate(PaintProgress) * (RustInitial + e);
float paintMask = (1.0 - smoothstep(paintEdge, paintEdge + e, N)) * step(0.001, PaintProgress);
if (PaintProgress >= 0.99) paintMask = 1.0;
if (PaintProgress >= 0.98) paintMask = 1.0;
// ВАЖНО: Доля повреждения, которая ЕЩЁ видна (не перекрыта краской).
// При завершении покраски (paintMask = 1) это значение строго равно 0 даже на полутонах!
float damageVisible = zone * (1.0 - paintMask);
// 4. Очаги ржавчины (лежат поверх всего, пока не счищены)
float rust = smoothstep(1.0 - RustAmount, 1.0 - RustAmount + e, N) * step(0.001, RustAmount);
// 4. Текущий остаток ржавчины
float rust = zone * smoothstep(1.0 - RustAmount, 1.0 - RustAmount + e, N) * step(0.001, RustAmount);
// Смешиваем заводскую краску с повреждением
float3 col = lerp(BaseColor, underColor, damageVisible);
float sm = lerp(PaintSmoothness, underSmooth, damageVisible);
float met = lerp(0.0, underMetal, damageVisible);
// Поверх накладываем оставшуюся ржавчину
col = lerp(col, RustColor, rust);
sm = lerp(sm, 0.1, rust);
sm = lerp(sm, 0.08, rust);
met = lerp(met, 0.0, rust);
Albedo = col;
@@ -77,14 +80,10 @@ void RepairSurface_half(
out half Metallic,
out half Smoothness)
{
float3 a;
float m;
float s;
float3 a; float m; float s;
RepairSurface_float(N, BaseColor, RustColor, RustInitial, RustAmount,
PuttyProgress, SandProgress, PaintProgress, PaintSmoothness, a, m, s);
Albedo = a;
Metallic = m;
Smoothness = s;
Albedo = a; Metallic = m; Smoothness = s;
}
#endif
@@ -215,8 +215,616 @@ MonoBehaviour:
m_SourceFontFilePath:
m_AtlasPopulationMode: 1
InternalDynamicOS: 0
m_GlyphTable: []
m_CharacterTable: []
m_GlyphTable:
- m_Index: 978
m_Metrics:
m_Width: 55
m_Height: 61
m_HorizontalBearingX: 4
m_HorizontalBearingY: 60
m_HorizontalAdvance: 62
m_GlyphRect:
m_X: 10
m_Y: 10
m_Width: 55
m_Height: 61
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 998
m_Metrics:
m_Width: 42
m_Height: 47
m_HorizontalBearingX: 3
m_HorizontalBearingY: 46
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 10
m_Y: 90
m_Width: 42
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1010
m_Metrics:
m_Width: 38
m_Height: 47
m_HorizontalBearingX: 3
m_HorizontalBearingY: 46
m_HorizontalAdvance: 43
m_GlyphRect:
m_X: 10
m_Y: 156
m_Width: 38
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1011
m_Metrics:
m_Width: 37
m_Height: 45
m_HorizontalBearingX: 1
m_HorizontalBearingY: 45
m_HorizontalAdvance: 39
m_GlyphRect:
m_X: 10
m_Y: 222
m_Width: 37
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1021
m_Metrics:
m_Width: 37
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 45
m_GlyphRect:
m_X: 10
m_Y: 286
m_Width: 37
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 995
m_Metrics:
m_Width: 37
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 46
m_GlyphRect:
m_X: 10
m_Y: 350
m_Width: 37
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1005
m_Metrics:
m_Width: 49
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 59
m_GlyphRect:
m_X: 10
m_Y: 414
m_Width: 49
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 993
m_Metrics:
m_Width: 45
m_Height: 47
m_HorizontalBearingX: 3
m_HorizontalBearingY: 46
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 66
m_Y: 222
m_Width: 45
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1017
m_Metrics:
m_Width: 59
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 69
m_GlyphRect:
m_X: 67
m_Y: 156
m_Width: 59
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1001
m_Metrics:
m_Width: 38
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 71
m_Y: 90
m_Width: 38
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1006
m_Metrics:
m_Width: 37
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 84
m_Y: 10
m_Width: 37
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1012
m_Metrics:
m_Width: 43
m_Height: 63
m_HorizontalBearingX: 0
m_HorizontalBearingY: 45
m_HorizontalAdvance: 43
m_GlyphRect:
m_X: 128
m_Y: 74
m_Width: 43
m_Height: 63
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 975
m_Metrics:
m_Width: 59
m_Height: 61
m_HorizontalBearingX: 4
m_HorizontalBearingY: 60
m_HorizontalAdvance: 67
m_GlyphRect:
m_X: 66
m_Y: 288
m_Width: 59
m_Height: 61
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1003
m_Metrics:
m_Width: 34
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 38
m_GlyphRect:
m_X: 140
m_Y: 10
m_Width: 34
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1009
m_Metrics:
m_Width: 40
m_Height: 64
m_HorizontalBearingX: 5
m_HorizontalBearingY: 46
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 78
m_Y: 368
m_Width: 40
m_Height: 64
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1020
m_Metrics:
m_Width: 51
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 62
m_GlyphRect:
m_X: 130
m_Y: 220
m_Width: 51
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1008
m_Metrics:
m_Width: 36
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 47
m_GlyphRect:
m_X: 145
m_Y: 156
m_Width: 36
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1007
m_Metrics:
m_Width: 42
m_Height: 47
m_HorizontalBearingX: 3
m_HorizontalBearingY: 46
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 78
m_Y: 451
m_Width: 42
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 980
m_Metrics:
m_Width: 54
m_Height: 60
m_HorizontalBearingX: 2
m_HorizontalBearingY: 59
m_HorizontalAdvance: 55
m_GlyphRect:
m_X: 190
m_Y: 74
m_Width: 54
m_Height: 60
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 997
m_Metrics:
m_Width: 49
m_Height: 62
m_HorizontalBearingX: 0
m_HorizontalBearingY: 45
m_HorizontalAdvance: 50
m_GlyphRect:
m_X: 137
m_Y: 368
m_Width: 49
m_Height: 62
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 999
m_Metrics:
m_Width: 58
m_Height: 45
m_HorizontalBearingX: 0
m_HorizontalBearingY: 45
m_HorizontalAdvance: 58
m_GlyphRect:
m_X: 193
m_Y: 10
m_Width: 58
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1024
m_Metrics:
m_Width: 41
m_Height: 45
m_HorizontalBearingX: 0
m_HorizontalBearingY: 45
m_HorizontalAdvance: 47
m_GlyphRect:
m_X: 139
m_Y: 449
m_Width: 41
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1004
m_Metrics:
m_Width: 45
m_Height: 46
m_HorizontalBearingX: 0
m_HorizontalBearingY: 45
m_HorizontalAdvance: 50
m_GlyphRect:
m_X: 199
m_Y: 449
m_Width: 45
m_Height: 46
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1016
m_Metrics:
m_Width: 34
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 45
m_GlyphRect:
m_X: 144
m_Y: 284
m_Width: 34
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 994
m_Metrics:
m_Width: 41
m_Height: 64
m_HorizontalBearingX: 5
m_HorizontalBearingY: 63
m_HorizontalAdvance: 49
m_GlyphRect:
m_X: 197
m_Y: 284
m_Width: 41
m_Height: 64
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 968
m_Metrics:
m_Width: 46
m_Height: 61
m_HorizontalBearingX: 2
m_HorizontalBearingY: 60
m_HorizontalAdvance: 52
m_GlyphRect:
m_X: 205
m_Y: 367
m_Width: 46
m_Height: 61
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 963
m_Metrics:
m_Width: 46
m_Height: 59
m_HorizontalBearingX: 7
m_HorizontalBearingY: 59
m_HorizontalAdvance: 57
m_GlyphRect:
m_X: 200
m_Y: 153
m_Width: 46
m_Height: 59
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1000
m_Metrics:
m_Width: 35
m_Height: 47
m_HorizontalBearingX: 2
m_HorizontalBearingY: 46
m_HorizontalAdvance: 39
m_GlyphRect:
m_X: 263
m_Y: 447
m_Width: 35
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1002
m_Metrics:
m_Width: 38
m_Height: 63
m_HorizontalBearingX: 5
m_HorizontalBearingY: 63
m_HorizontalAdvance: 48
m_GlyphRect:
m_X: 257
m_Y: 231
m_Width: 38
m_Height: 63
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1013
m_Metrics:
m_Width: 65
m_Height: 80
m_HorizontalBearingX: 3
m_HorizontalBearingY: 62
m_HorizontalAdvance: 71
m_GlyphRect:
m_X: 270
m_Y: 313
m_Width: 65
m_Height: 80
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 996
m_Metrics:
m_Width: 24
m_Height: 45
m_HorizontalBearingX: 5
m_HorizontalBearingY: 45
m_HorizontalAdvance: 31
m_GlyphRect:
m_X: 263
m_Y: 74
m_Width: 24
m_Height: 45
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
- m_Index: 1023
m_Metrics:
m_Width: 56
m_Height: 47
m_HorizontalBearingX: 5
m_HorizontalBearingY: 46
m_HorizontalAdvance: 65
m_GlyphRect:
m_X: 265
m_Y: 138
m_Width: 56
m_Height: 47
m_Scale: 1
m_AtlasIndex: 0
m_ClassDefinitionType: 0
m_CharacterTable:
- m_ElementType: 1
m_Unicode: 1057
m_GlyphIndex: 978
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1077
m_GlyphIndex: 998
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1089
m_GlyphIndex: 1010
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1090
m_GlyphIndex: 1011
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1100
m_GlyphIndex: 1021
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1074
m_GlyphIndex: 995
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1084
m_GlyphIndex: 1005
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1072
m_GlyphIndex: 993
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1096
m_GlyphIndex: 1017
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1080
m_GlyphIndex: 1001
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1085
m_GlyphIndex: 1006
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1091
m_GlyphIndex: 1012
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1054
m_GlyphIndex: 975
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1082
m_GlyphIndex: 1003
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1088
m_GlyphIndex: 1009
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1099
m_GlyphIndex: 1020
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1087
m_GlyphIndex: 1008
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1086
m_GlyphIndex: 1007
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1059
m_GlyphIndex: 980
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1076
m_GlyphIndex: 997
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1078
m_GlyphIndex: 999
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1103
m_GlyphIndex: 1024
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1083
m_GlyphIndex: 1004
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1095
m_GlyphIndex: 1016
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1073
m_GlyphIndex: 994
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1047
m_GlyphIndex: 968
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1042
m_GlyphIndex: 963
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1079
m_GlyphIndex: 1000
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1081
m_GlyphIndex: 1002
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1092
m_GlyphIndex: 1013
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1075
m_GlyphIndex: 996
m_Scale: 1
- m_ElementType: 1
m_Unicode: 1102
m_GlyphIndex: 1023
m_Scale: 1
m_AtlasTextures:
- {fileID: 28268798066460806}
m_AtlasTextureIndex: 0
@@ -227,12 +835,240 @@ MonoBehaviour:
m_AtlasHeight: 512
m_AtlasPadding: 9
m_AtlasRenderMode: 4169
m_UsedGlyphRects: []
m_FreeGlyphRects:
m_UsedGlyphRects:
- m_X: 0
m_Y: 0
m_Width: 74
m_Height: 80
- m_X: 0
m_Y: 80
m_Width: 61
m_Height: 66
- m_X: 0
m_Y: 146
m_Width: 57
m_Height: 66
- m_X: 0
m_Y: 212
m_Width: 56
m_Height: 64
- m_X: 0
m_Y: 276
m_Width: 56
m_Height: 64
- m_X: 0
m_Y: 340
m_Width: 56
m_Height: 64
- m_X: 0
m_Y: 404
m_Width: 68
m_Height: 64
- m_X: 56
m_Y: 212
m_Width: 64
m_Height: 66
- m_X: 57
m_Y: 146
m_Width: 78
m_Height: 64
- m_X: 61
m_Y: 80
m_Width: 57
m_Height: 64
- m_X: 74
m_Y: 0
m_Width: 56
m_Height: 64
- m_X: 118
m_Y: 64
m_Width: 62
m_Height: 82
- m_X: 56
m_Y: 278
m_Width: 78
m_Height: 80
- m_X: 130
m_Y: 0
m_Width: 53
m_Height: 64
- m_X: 68
m_Y: 358
m_Width: 59
m_Height: 83
- m_X: 120
m_Y: 210
m_Width: 70
m_Height: 64
- m_X: 135
m_Y: 146
m_Width: 55
m_Height: 64
- m_X: 68
m_Y: 441
m_Width: 61
m_Height: 66
- m_X: 180
m_Y: 64
m_Width: 73
m_Height: 79
- m_X: 127
m_Y: 358
m_Width: 68
m_Height: 81
- m_X: 183
m_Y: 0
m_Width: 77
m_Height: 64
- m_X: 129
m_Y: 439
m_Width: 60
m_Height: 64
- m_X: 189
m_Y: 439
m_Width: 64
m_Height: 65
- m_X: 134
m_Y: 274
m_Width: 53
m_Height: 64
- m_X: 187
m_Y: 274
m_Width: 60
m_Height: 83
- m_X: 195
m_Y: 357
m_Width: 65
m_Height: 80
- m_X: 190
m_Y: 143
m_Width: 65
m_Height: 78
- m_X: 253
m_Y: 437
m_Width: 54
m_Height: 66
- m_X: 247
m_Y: 221
m_Width: 57
m_Height: 82
- m_X: 260
m_Y: 303
m_Width: 84
m_Height: 99
- m_X: 253
m_Y: 64
m_Width: 43
m_Height: 64
- m_X: 255
m_Y: 128
m_Width: 75
m_Height: 66
m_FreeGlyphRects:
- m_X: 61
m_Y: 144
m_Width: 57
m_Height: 2
- m_X: 74
m_Y: 64
m_Width: 44
m_Height: 16
- m_X: 56
m_Y: 358
m_Width: 12
m_Height: 46
- m_X: 57
m_Y: 210
m_Width: 63
m_Height: 2
- m_X: 0
m_Y: 507
m_Width: 511
m_Height: 4
- m_X: 0
m_Y: 468
m_Width: 68
m_Height: 43
- m_X: 127
m_Y: 439
m_Width: 2
m_Height: 2
- m_X: 129
m_Y: 504
m_Width: 382
m_Height: 7
- m_X: 129
m_Y: 503
m_Width: 60
m_Height: 8
- m_X: 120
m_Y: 274
m_Width: 14
m_Height: 4
- m_X: 134
m_Y: 338
m_Width: 53
m_Height: 20
- m_X: 134
m_Y: 357
m_Width: 61
m_Height: 1
- m_X: 180
m_Y: 143
m_Width: 10
m_Height: 3
- m_X: 253
m_Y: 503
m_Width: 258
m_Height: 8
- m_X: 195
m_Y: 437
m_Width: 58
m_Height: 2
- m_X: 190
m_Y: 221
m_Width: 57
m_Height: 53
- m_X: 307
m_Y: 402
m_Width: 204
m_Height: 109
- m_X: 344
m_Y: 0
m_Width: 167
m_Height: 511
- m_X: 247
m_Y: 303
m_Width: 13
m_Height: 54
- m_X: 260
m_Y: 402
m_Width: 251
m_Height: 35
- m_X: 260
m_Y: 0
m_Width: 251
m_Height: 64
- m_X: 304
m_Y: 194
m_Width: 207
m_Height: 109
- m_X: 330
m_Y: 0
m_Width: 181
m_Height: 303
- m_X: 253
m_Y: 128
m_Width: 2
m_Height: 15
- m_X: 255
m_Y: 194
m_Width: 256
m_Height: 27
- m_X: 296
m_Y: 0
m_Width: 215
m_Height: 128
m_FontFeatureTable:
m_MultipleSubstitutionRecords: []
m_LigatureSubstitutionRecords: []
@@ -5022,6 +5858,21 @@ MonoBehaviour:
m_XAdvance: 0
m_YAdvance: 0
m_FeatureLookupFlags: 0
- m_FirstAdjustmentRecord:
m_GlyphIndex: 979
m_GlyphValueRecord:
m_XPlacement: 0
m_YPlacement: 0
m_XAdvance: -3.7792969
m_YAdvance: 0
m_SecondAdjustmentRecord:
m_GlyphIndex: 1008
m_GlyphValueRecord:
m_XPlacement: 0
m_YPlacement: 0
m_XAdvance: 0
m_YAdvance: 0
m_FeatureLookupFlags: 0
m_MarkToBaseAdjustmentRecords: []
m_MarkToMarkAdjustmentRecords: []
m_ShouldReimportFontFeatures: 0
@@ -5113,9 +5964,9 @@ Texture2D:
Hash: 00000000000000000000000000000000
m_IsAlphaChannelOptional: 0
serializedVersion: 4
m_Width: 1
m_Height: 1
m_CompleteImageSize: 1
m_Width: 512
m_Height: 512
m_CompleteImageSize: 262144
m_MipsStripped: 0
m_TextureFormat: 1
m_MipCount: 1
@@ -5140,8 +5991,8 @@ Texture2D:
m_LightmapFormat: 0
m_ColorSpace: 0
m_PlatformBlob:
image data: 1
_typelessdata: 00
image data: 262144
_typelessdata: 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030607090b0d0f1111121313121111100d0b090706030000000000000000000000000000000000000000000000000000000000000000040613131313131313130d0c0a070200000000000000000000000000040613131313131313130d0c0a070200000000000000000000000003060809131313131313130b0a0805000000000000000004080c0e0f13131313131313100f0d09050000000000000000000000000105090b0b131313131313131207060401000000000000000000030613131313131313130d0d0b0702000000000000000106090b0c1313131313131312070604010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000104060c10121315181a1c1d1e1f1f201f1e1d1c1a18151312100c0604000000000000000000000000000000000000000000000000000001070c101320202020202020201a1917130e0700000000000000000001070c101320202020202020201a1917130e08000000000000000000040a0f13151620202020202020181715110c060000000002090f14181b1b202020202020201d1c1915100a03000000000000000000060c11151718202020202020201f1413110d08010000000000060c101220202020202020201a1917130e080100000000070d12161819202020202020201e1413100d0701000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001070d1113171c1f20222427292a2b2c2c2c2c2b2a29272522201f1c1713100c070000000000000000000000000000000000000000000000030b12181c1f2d2d2d2d2d2d2d2d2626231f19120a01000000000000030b12181c1f2d2d2d2d2d2d2d2d2726231f19120a02000000000000070f151b1f22222d2d2d2d2d2d2d2424211d1710090000030b131a202427282d2d2d2d2d2d2d292826211b140c04000000000000000911181d2124252d2d2d2d2d2d2d2c21201d19130c040000030a11171c1f2d2d2d2d2d2d2d2d2726231f19120a0200010911181e2225262d2d2d2d2d2d2d2b20201d18120c04000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003090e13181d2023282c2d2f31333637383839393838373634312f2d2c28231f1c18120d080200000000000000000000000000000000000000030d151d23292c393939393939393933322f2a241c130a0000000000030d151d23292c393939393939393933322f2a241c140a000000000007101920272b2e2f3939393939393931302d28221b1209000b151d252c313435393939393939393635322d261e160c03000000000009121b22292e313239393939393939382d2c29241e160d04030c151c23282c393939393939393934332f2b241c140a0009131b23292e313239393939393939382d2c29241d160d040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000Line truncated
m_StreamData:
serializedVersion: 2
offset: 0
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ce8312af2a603954dad461496f4aff05
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d84dbef94394f4647b2278fa18a8099e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+13 -1
View File
@@ -1,5 +1,6 @@
{
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.2.0",
"com.unity.ai.navigation": "2.0.14",
"com.unity.collab-proxy": "2.13.6",
"com.unity.ide.rider": "3.0.38",
@@ -46,7 +47,18 @@
"com.unity.modules.video": "1.0.0",
"com.unity.modules.wind": "1.0.0",
"com.unity.modules.xr": "1.0.0",
"com.ivanmurzak.unity.mcp": "0.93.2"
"com.ivanmurzak.unity.mcp.animation": "2.0.1",
"com.ivanmurzak.unity.mcp.cinemachine": "2.0.1",
"com.ivanmurzak.unity.mcp.inputsystem": "2.0.1",
"com.ivanmurzak.unity.mcp.navigation": "2.0.1",
"com.ivanmurzak.unity.mcp.probuilder": "2.0.1",
"com.unity.probuilder": "6.1.3",
"com.ivanmurzak.unity.mcp.splines": "2.0.1",
"com.ivanmurzak.unity.mcp.particlesystem": "2.0.1",
"com.ivanmurzak.unity.mcp.terrain": "2.0.1",
"com.ivanmurzak.unity.mcp.tilemap": "2.0.1",
"com.unity.2d.tilemap.extras": "7.0.1",
"com.ivanmurzak.unity.mcp.timeline": "2.0.1"
},
"scopedRegistries": [
{
+168 -1
View File
@@ -1,7 +1,7 @@
{
"dependencies": {
"com.ivanmurzak.unity.mcp": {
"version": "0.93.2",
"version": "1.2.0",
"depth": 0,
"source": "registry",
"dependencies": {
@@ -11,6 +11,128 @@
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.animation": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.modules.animation": "1.0.0"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.cinemachine": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.cinemachine": "3.1.6"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.inputsystem": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.1",
"com.unity.inputsystem": "1.8.2"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.navigation": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.ai.navigation": "1.1.7"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.particlesystem": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.modules.particlesystem": "1.0.0"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.probuilder": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.probuilder": "5.2.4"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.splines": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.splines": "2.8.4"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.terrain": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.modules.terrain": "1.0.0",
"com.unity.modules.terrainphysics": "1.0.0"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.tilemap": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.2d.tilemap.extras": "3.1.3"
},
"url": "https://package.openupm.com"
},
"com.ivanmurzak.unity.mcp.timeline": {
"version": "2.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.ivanmurzak.unity.mcp": "1.0.0",
"com.unity.timeline": "1.8.12"
},
"url": "https://package.openupm.com"
},
"com.unity.2d.tilemap": {
"version": "1.0.0",
"depth": 1,
"source": "builtin",
"dependencies": {
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.uielements": "1.0.0"
}
},
"com.unity.2d.tilemap.extras": {
"version": "7.0.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.unity.2d.tilemap": "1.0.0",
"com.unity.modules.tilemap": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0"
},
"url": "https://packages.unity.com"
},
"com.unity.ai.navigation": {
"version": "2.0.14",
"depth": 0,
@@ -26,6 +148,15 @@
"source": "builtin",
"dependencies": {}
},
"com.unity.cinemachine": {
"version": "6.6.0",
"depth": 1,
"source": "builtin",
"dependencies": {
"com.unity.splines": "2.8.4",
"com.unity.modules.imgui": "1.0.0"
}
},
"com.unity.collab-proxy": {
"version": "2.13.6",
"depth": 0,
@@ -83,6 +214,12 @@
},
"url": "https://packages.unity.com"
},
"com.unity.mathematics": {
"version": "1.4.0",
"depth": 2,
"source": "builtin",
"dependencies": {}
},
"com.unity.nuget.mono-cecil": {
"version": "1.11.6",
"depth": 3,
@@ -90,6 +227,18 @@
"dependencies": {},
"url": "https://packages.unity.com"
},
"com.unity.probuilder": {
"version": "6.1.3",
"depth": 0,
"source": "registry",
"dependencies": {
"com.unity.shadergraph": "17.0.3",
"com.unity.modules.imgui": "1.0.0",
"com.unity.modules.physics": "1.0.0",
"com.unity.settings-manager": "1.0.3"
},
"url": "https://packages.unity.com"
},
"com.unity.profiling.core": {
"version": "1.0.3",
"depth": 2,
@@ -133,6 +282,13 @@
"dependencies": {},
"url": "https://packages.unity.com"
},
"com.unity.settings-manager": {
"version": "2.1.1",
"depth": 1,
"source": "registry",
"dependencies": {},
"url": "https://packages.unity.com"
},
"com.unity.shadergraph": {
"version": "17.6.0",
"depth": 1,
@@ -143,6 +299,17 @@
"com.unity.graph-authoring": "1.0.0"
}
},
"com.unity.splines": {
"version": "2.9.0",
"depth": 1,
"source": "registry",
"dependencies": {
"com.unity.mathematics": "1.2.1",
"com.unity.modules.imgui": "1.0.0",
"com.unity.settings-manager": "1.0.3"
},
"url": "https://packages.unity.com"
},
"com.unity.test-framework": {
"version": "1.8.0",
"depth": 0,
@@ -0,0 +1,61 @@
{
"m_Dictionary": {
"m_DictionaryValues": [
{
"type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "editor.stripProBuilderScriptsOnBuild",
"value": "{\"m_Value\":true}"
},
{
"type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "experimental.enabled",
"value": "{\"m_Value\":false}"
},
{
"type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "editor.backFaceSelectEnabled",
"value": "{\"m_Value\":false}"
},
{
"type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "lightmapping.autoUnwrapLightmapUV",
"value": "{\"m_Value\":true}"
},
{
"type": "System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "ShapeComponent.ResetSettings",
"value": "{\"m_Value\":false}"
},
{
"type": "UnityEngine.ProBuilder.SelectMode, Unity.ProBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"key": "s_SelectMode",
"value": "{\"m_Value\":4}"
},
{
"type": "UnityEngine.ProBuilder.LogLevel, Unity.ProBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"key": "log.level",
"value": "{\"m_Value\":3}"
},
{
"type": "UnityEngine.ProBuilder.LogOutput, Unity.ProBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"key": "log.output",
"value": "{\"m_Value\":1}"
},
{
"type": "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"key": "log.path",
"value": "{\"m_Value\":\"ProBuilderLog.txt\"}"
},
{
"type": "UnityEngine.ProBuilder.SemVer, Unity.ProBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"key": "about.identifier",
"value": "{\"m_Value\":{\"m_Major\":6,\"m_Minor\":1,\"m_Patch\":3,\"m_Build\":-1,\"m_Type\":\"\",\"m_Metadata\":\"\",\"m_Date\":\"\"}}"
},
{
"type": "UnityEngine.ProBuilder.SemVer, Unity.ProBuilder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
"key": "preferences.version",
"value": "{\"m_Value\":{\"m_Major\":6,\"m_Minor\":1,\"m_Patch\":3,\"m_Build\":-1,\"m_Type\":\"\",\"m_Metadata\":\"\",\"m_Date\":\"\"}}"
}
]
}
}
+19 -19
View File
@@ -835,25 +835,25 @@ PlayerSettings:
webEnableSubmoduleStrippingCompatibility: 0
webProgressiveAssetLoading: 0
scriptingDefineSymbols:
Android: UNITY_MCP_READY;UNITY_MCP_DEPS_6
EmbeddedLinux: UNITY_MCP_READY;UNITY_MCP_DEPS_6
GameCoreScarlett: UNITY_MCP_READY;UNITY_MCP_DEPS_6
GameCoreXboxOne: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Kepler: UNITY_MCP_READY;UNITY_MCP_DEPS_6
LinuxHeadlessSimulation: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Nintendo Switch: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Nintendo Switch 2: UNITY_MCP_READY;UNITY_MCP_DEPS_6
PS4: UNITY_MCP_READY;UNITY_MCP_DEPS_6
PS5: UNITY_MCP_READY;UNITY_MCP_DEPS_6
QNX: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Server: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Standalone: UNITY_MCP_READY;UNITY_MCP_DEPS_6
VisionOS: UNITY_MCP_READY;UNITY_MCP_DEPS_6
WebGL: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Windows Store Apps: UNITY_MCP_READY;UNITY_MCP_DEPS_6
XboxOne: UNITY_MCP_READY;UNITY_MCP_DEPS_6
iPhone: UNITY_MCP_READY;UNITY_MCP_DEPS_6
tvOS: UNITY_MCP_READY;UNITY_MCP_DEPS_6
Android: UNITY_MCP_READY;UNITY_MCP_DEPS_12
EmbeddedLinux: UNITY_MCP_READY;UNITY_MCP_DEPS_12
GameCoreScarlett: UNITY_MCP_READY;UNITY_MCP_DEPS_12
GameCoreXboxOne: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Kepler: UNITY_MCP_READY;UNITY_MCP_DEPS_12
LinuxHeadlessSimulation: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Nintendo Switch: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Nintendo Switch 2: UNITY_MCP_READY;UNITY_MCP_DEPS_12
PS4: UNITY_MCP_READY;UNITY_MCP_DEPS_12
PS5: UNITY_MCP_READY;UNITY_MCP_DEPS_12
QNX: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Server: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Standalone: UNITY_MCP_READY;UNITY_MCP_DEPS_12
VisionOS: UNITY_MCP_READY;UNITY_MCP_DEPS_12
WebGL: UNITY_MCP_READY;UNITY_MCP_DEPS_12
Windows Store Apps: UNITY_MCP_READY;UNITY_MCP_DEPS_12
XboxOne: UNITY_MCP_READY;UNITY_MCP_DEPS_12
iPhone: UNITY_MCP_READY;UNITY_MCP_DEPS_12
tvOS: UNITY_MCP_READY;UNITY_MCP_DEPS_12
additionalCompilerArguments: {}
platformArchitecture: {}
scriptingBackend: