using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour
{
public Transform target;
public float force = 1f;
public Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
var distance = Vector3.Distance(transform.position, target.position);
rb.AddForce(transform.forward * force);
}
}
In the screenshot the components on the transform. I added a Rigidbody and freezed the position on X and Y. Now the transform is moving straight getting force slowly.
The problem is if I’m not locking the X and Y on the Constraints the transform will fall down. In the other hand locking the X and Y will prevent it to rotate or move to specific directions isn’t it ?
Now I want to add few stuff to it :
-
To make the transform to move to a target not just to move nonostop.
-
To make that when the transform reach a specific speed then stay at this speed for example speed 7.
-
To make that when the transform for example is in distance 10 from the target start removed force slowly until the transform is reaching the target then the force should be 0 so the transform will stop slowly smooth at the target.
-
To add a rotation to the transform when the transform start moving to the target he also will rotate facing the target.
“The problem is if I’m not locking the X and Y on the Constraints the transform will fall down. In the other hand locking the X and Y will prevent it to rotate or move to specific directions isn’t it ?”
Y is the down direction, so your options are: Turn off gravity, constrain the Y position or use a script to check the y position and restore it as necessary.
For your other questions:-
You will find it useful to be aware of these:
Equations of motion - Wikipedia (look past the rather daunting start to the section “Constant translational acceleration in a straight line”)
F = m a (force = mass * acceleration, i.e. a = F/m)
From this information you can see how acceleration is related to force and mass and use some fairly simple equations of motion to figure out the effect of acceleration and velocity on position over time.
ForceMode will save you most of the pain, by allowing you to specify a velocity change.
You can directly set the rigidbody velocity (e.g. rb.velocity = new Vector3(1, 0, 0); ), this is not usually the best approach as you may interfere with existing physics events. This will also allow you to Unity - Scripting API: Vector3.ClampMagnitude and/or control velocity by scaling a normalized vector. All will require some care in order to not create unexpected effects.
If your rigidbody can be kinematic, then you could use MovePosition, but be aware that it will then not collide with your environment (although other, non-kinematic rigid bodies will collide with it).Unity - Scripting API: Rigidbody.MovePosition