Hey guys
Just wondering how I would get an object to move to a certain Vector3 point in the game and control the speed to which it moves there?
I can do…
transform.Translate(0, 0, 2 * Time.deltaTime);
to get it to move at a certain speed (not to position)
and also…
transform.position - Vector3(0,0,0)
to get it to my point immediately (too fast)
so just wondering if anyone could give me a hand with how to combine the two
Thanks!
Here’s a simple example:
// Drag a game object placed at the desired position there.
var target : Transform;
var speed = 0.2; // Speed in units per second
function Update() {
// If no target is set, return immediately
if( ! target )
return;
// First you get the vector from the current position
// to the destination, and normalize it so you
// get the direction:
var dir=(target.position - transform.position).normalized;
// Then add the direction * the speed to the current position:
transform.position += dir * speed * Time.deltaTime;
}
1 Like
Wow this works awesome, Thanks!!
Just one more question
I want to have the ball moving from wherever it is on the court, and move it in front of the server in its path and then have it move forwards (the action of serving) which triggers the collision and starts the match. This is the example of the code which I am using, and I understand that the ball is moving towards the target for one frame only and then the servers starts moving forward as he should, I am just unsure as to how to wait until the ball moves the whole distance to the target before triggering another action (in this case a collison). I have been looking at the WaitForSeconds function but having no luck with it (if this is what I want to be using!)
var dir;
function Update() {
//remove gravity to move ball to server
if(MatchScriptVariables.pointover == true) {
rigidbody.useGravity = false;
}
//the time of the game to move the ball to the setter
if(MatchScriptVariables.gametime == 0) {
dir=(Vector3(115,4,-58) - transform.position).normalized;
transform.position += dir * 25 * Time.deltaTime;
//change the time of the game to the servers ball toss preparing to serve
}
MatchScriptVariables.gametime = 1;
}