For now I am using:
Vector3 targetPos = new Vector3(43.4,2,2);
void Update(){
transform.position = Vector3.Lerp(transform.position,targetPos,(Time.deltaTime*3)/Vector3.Distance(targetPos,transform.position);
}
This works nicely , but i need rigidbody with correct velocity and all simulations.
I don’t need rigidbody.MovePosition or rigidbody.position because that works but that doesn’t change velocity.
I need something that will return velocity.
To calculate a directional Vector :
var dir : Vector3 = target.position - transform.position;
to give this vector a magnitude in relation to speed, normalize it then multiply the result by the speed :
var dir : Vector3 = (target.position - transform.position).normalized * speed;
finally, simply apply the vector to the velocity variable of the rigidbody component :
rigidbody.velocity = dir;
Rigidbody :
Vector information :
To see if the rigidbody has reached the target, you could look into how waypoints are used and implemented. But here’s a quick and dirty way to check if a waypoint has been reached :
#pragma strict
var target : Transform;
var speed : float = 2.0;
private var desiredVelocity : Vector3;
private var lastSqrMag : float;
function Start()
{
// calculate directional vector to target
var directionalVector : Vector3 = (target.position - transform.position).normalized * speed;
// reset lastSqrMag
lastSqrMag = Mathf.Infinity;
// apply to rigidbody velocity
desiredVelocity = directionalVector;
}
function Update()
{
// check the current sqare magnitude
var sqrMag : float = (target.position - transform.position).sqrMagnitude;
// check this against the lastSqrMag
// if this is greater than the last,
// rigidbody has reached target and is now moving past it
if ( sqrMag > lastSqrMag )
{
// rigidbody has reached target and is now moving past it
// stop the rigidbody by setting the velocity to zero
desiredVelocity = Vector3.zero;
}
// make sure you update the lastSqrMag
lastSqrMag = sqrMag;
}
function FixedUpdate()
{
rigidbody.velocity = desiredVelocity;
}
Assuming you are using a rigidbody, and assuming there are no other forces (like gravity) impacting the rigidbody, you can do something like:
rigidbody.velocity = (targetPos - transform.position).normalized * speed;
Note this is done once, not in every frame. And it will not stop at your targetPos unless you write code to make it stop. ‘speed’ is a variable you define, will be in units per second, and for your question would be 2.0.