- Home /
from world to local coordinates bouncing ball?
Hi,
I would like my character to bounce constantly, even if its parent moves up or down. If I try the bouncing effect on a constant y axis in local space, it works fine. But if the character goes down, the ball stays up in the air, because its "anchor point" has not changed. So I would like to use the character's y position for my effect. How could I then update the local coordinates with the parent's y position (which is in world space)? TransformPoint is to go from local to world, how to do the inverse? Or any other solution?
Here is the code that works in local space :
coef += 0.1f;
//Vector3 trPos = transform.position;
//trPos.y = posY + (Mathf.Sin(coef) * multSin);//local space : goes up and down
Vector3 trPos = transform.TransformPoint(transform.parent.position);//cannot use this to update local coordinates
trPos.y = trPos.y + (Mathf.Sin(coef) * multSin);
//transform.position = … new Vector3(trPos.x, trPos.y, trPos.z );
Thanks for your help
Answer by robertbu · Jul 17, 2013 at 03:43 PM
If I understand what you want to do correctly, what you want to do is to Transform.localPosition:
public class Bounce : MonoBehaviour {
public float speed = 1.0f;
public float magnitude = 2.0f;
void Update() {
Vector3 v3 = transform.localPosition;
v3.y = Mathf.Sin(Time.time * speed) * magnitude;
transform.localPosition = v3;
}
}
If you want more of a bounce like a ball hitting a surface, change the calculation to:
v3.y = Mathf.Abs(Mathf.Sin(Time.time * speed) * magnitude);
@robertbu thanks a lot robertbu, I misunderstood that transform.position was already in world space. Thanks for your help, it works fine!
If you use Time.time or Time.deltaTime, then this code needs to be in Update() or if there was some need, LateUpdate(). FixedUpdate() is generally for Physics operations (which this is not). If for some reason you needed it in FixedUpdate(), you would use Time.fixedDeltaTime.
Your answer
Follow this Question
Related Questions
How do i move an object relative to another objects axis. 2 Answers
Keeping raycast position and rotation equal as gameObject 1 Answer
Trying to position a world space menu in front of the camera whilst ignoring the camera's tilt angle 1 Answer
World to local Inversion not working as I expect 0 Answers
How to get max and min points of a game object on the x and z axis? 3 Answers