| | | 1 | | using UnityEngine; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Move an object using velocity |
| | | 5 | | /// </summary> |
| | | 6 | | [RequireComponent(typeof(Rigidbody))] |
| | | 7 | | public class MoveWithVelocity : MonoBehaviour |
| | | 8 | | { |
| | | 9 | | [Tooltip("The speed at which the object is moved")] |
| | 5 | 10 | | public float speed = 1.0f; |
| | | 11 | | |
| | | 12 | | [Tooltip("Controls the direction of movement")] |
| | 5 | 13 | | public Transform origin = null; |
| | | 14 | | |
| | 5 | 15 | | private Vector3 inputVelocity = Vector3.zero; |
| | 5 | 16 | | private Rigidbody rigidBody = null; |
| | | 17 | | |
| | | 18 | | private void Awake() |
| | 2 | 19 | | { |
| | 2 | 20 | | rigidBody = GetComponent<Rigidbody>(); |
| | 2 | 21 | | } |
| | | 22 | | |
| | | 23 | | private void FixedUpdate() |
| | 4183 | 24 | | { |
| | 4183 | 25 | | ApplyVelocity(); |
| | 4183 | 26 | | } |
| | | 27 | | |
| | | 28 | | private void ApplyVelocity() |
| | 4183 | 29 | | { |
| | 4183 | 30 | | Vector3 targetVelocity = inputVelocity * speed; |
| | 4183 | 31 | | targetVelocity = origin.TransformDirection(targetVelocity); |
| | | 32 | | |
| | 4183 | 33 | | Vector3 velocityChange = targetVelocity - rigidBody.velocity; |
| | 4183 | 34 | | rigidBody.AddForce(velocityChange, ForceMode.VelocityChange); |
| | 4183 | 35 | | } |
| | | 36 | | |
| | | 37 | | public void SetRightVelocity(float value) |
| | 0 | 38 | | { |
| | 0 | 39 | | inputVelocity.x = value; |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | public void SetForwardVelocity(float value) |
| | 0 | 43 | | { |
| | 0 | 44 | | inputVelocity.z = value; |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | public void SetUpVelocity(float value) |
| | 0 | 48 | | { |
| | 0 | 49 | | inputVelocity.y = value; |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | private void OnValidate() |
| | 5 | 53 | | { |
| | 5 | 54 | | if (!origin) |
| | 0 | 55 | | origin = transform; |
| | 5 | 56 | | } |
| | | 57 | | } |