- Home /
Lerp & jumping with sin/cos
I've just started messing around with moving cubes on a plane in response to keyboard input. I'm trying to keep things simple with no physics, movement of 1 metre/unit at a time etc. Think Frogger ;)
In Update(), I'm calling GetKeyDown and if an arrow key is pressed, calculating a new Vector3 for the target position and then calling Lerp.
transform.position = Vector3.Lerp (transform.position, target, (Time.time - startTime) / duration);
This works well and my cube slides in the desired direction.
I now want to make the cube "hop" in the air by applying a sin offset to my transform.position.y, but just can't figure it out. I think I need to track my movement lerp value in either X (for left/right movement) or Z (for north/south movement). From that, I somehow need to multiply by sin or cos to get the Y offset, then apply it to the transform.
Any thoughts or two-line code samples appreciated. I do intend to look at CharacterController tonight btw.
Answer by Owen-Reynolds · Jan 09, 2012 at 05:30 PM
In real trig (the kind sin/cos uses) 0 degrees faces right, goes counter-clockwise, using radians (PI radians is 180 degrees.) Sin is the y-coord, and cos is the x-coord, both between from -1 and 1. So, as you rotate from 0 to PI radians, sin goes from 0 to 1 to 0. This is regular high-school math, or see Wikipedia. It's a lot easier to tweak if you can visualize it.
The standard way to hop with sin (yes, real hops do make a sin wave) is: y=HT*sin(A) where A goes from 0 to PI. Since you already have a Lerp value going from 0 to 1, you just need to scale it:
y = jumpHT * Mathf.Sin( Mathf.PI * ((Time.time - startTime)/duration) );
^^^^^ your old lerp value ^^^^^
Thank you Owen. That's almost exactly what I worked out on pen and paper about 2 hours after I posted. As it's 30 years since high school, I went back to basics for some revision :)
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
A better way to do jumping? 2 Answers
Player movement 0 Answers
Controlling direction while jumping using CharacterController 1 Answer
TERA style movement 1 Answer