- Home /
Move one object to anothers position over time.
I'm trying to move my FPS object to a new location quickly, roughly 2-3 times its running speed.
I currently have this to move his position
Player.transform.position.y = hit.transform.position.y+5; Player.transform.position.x = hit.transform.position.x; Player.transform.position.z = hit.transform.position.z;
However that obviously moves him instantly. How would I get him to move at the desired speed?
I tried using Lerp but it still jumps him there instantly.
Here's how I added it into my code, should I split the other stuff outta the update function and leave just the lerp in?
function Update () {
var hit: RaycastHit;
if(Physics.Raycast(Gun.transform.position, Gun.transform.forward, hit)){
if(hit.transform.tag == 'JumpTo'){
Text.guiTexture.enabled = true;
if(Input.GetButtonDown("Fire1")){
var distance = Vector3.Distance(Player.transform.position,hit.transform.position);
if(distance < 17)
Player.transform.position = Vector3.Lerp(Player.transform.position, hit.transform.position+(Vector3.up*5), Time.time);
}
}
else
Text.guiTexture.enabled = false;
}
}
Don't use Lerp with Time.time - that just moves it to the end position if the game has been running for more than 1 second. See this article on Unity Gems
Thanks for the link, I can see that being very useful for me :p. However using those in my script only moves the character whilst the mouse is pressed down, i guess cause its inside the if(Input clause.
How would I stop this? Could I make a new function and pass the positions in?
You could make a targetPosition when the button is down and then do the Lerp to the target position outside of the raycast if - so perhaps at the bottom of your Update function.
Okay I think I should be able to get that sorted. Only other problem I'm having is using Lepr my character slides along the ground, I need him to also move up too as 90% of the targets will be above him.
$$anonymous$$oving my guy to hit.point+(Vector3.up*5); moves him to exaclty where I want him, but using that in the Lerp he just slides.
Any idea why or how I could stop this?
Answer by sparkzbarca · Dec 10, 2012 at 04:09 PM
for an FPS you should probably be using a charactercontroller for the player and then you can use
Player.charactercontroller.simplemove(speed * direction)
you can use slerp to move that transform but even moving slowly moving a transform directly TELEPORTS the object. It makes no attempt to check for collision and will go straight through any object in the game.
Answer by Jake.OConnor · Dec 10, 2012 at 07:12 PM
You can use the Vector3.Lerp() function to lerp between the starting and target position over a given period of time, or if you need more specific controls you can use the Lerp function in Mathf. (You'll need to use the Lerp in one of your update functions to smooth out the movement over a number of frames.)