filipe moita filipe moita - 1 year ago 75
C# Question

Control begin and end point object between 2 points

im trying to move a object in unity between 2 points, and at the moment it kinda works strange, i read the documentation and it says that the object begin point is (0,0,0) so my object goes under my other mesh that i have there, and the end point i can actually control, in my case it is 10, i want the object to move between 1.5 and 10(not 0 to 10)
i have this

void Update () {
transform.position = new Vector3(transform.position.x,Mathf.PingPong(Time.time,10.0f), transform.position.z);

when i try to put speed on the ball doing this:

void Update () {
transform.position = new Vector3(transform.position.x,Mathf.PingPong(Time.time,10.0f) * 10, transform.position.z);

the object does not colide and goes back at the end point it just stop looping and never came back how can i correct this 2 problems?

Answer Source

If your object has a collider, I suggest you move it via its Rigidbody rather than its Transform, to avoid potential collision issues. Try this:

public float MinY = 1.5f; // y position of start point
public float MaxY = 10f; // y position of end point
public float PingPongTime = 1f; // how much time to wait before reverse
public Rigidbody rb; // reference to the rigidbody

void Update()
     //get a value between 0 and 1
     float normalizedTime = Mathf.PingPong(Time.time, PingPongTime) / PingPongTime;
     //then multiply it by the delta between start and end point, and add start point to the result
     float yPosition = normalizedTime * (MaxY - MinY) + MinY;
     //finally update position using rigidbody 
     rb.MovePosition(new Vector3(rb.position.x, yPosition, rb.position.z));

Here you have a better control on the distance to travel, and the speed. Actually I didn't get exactly what are the problem you faced. But don't forget here and in your try, that you are directly modifying the position of the object, not adding forces or else.

Hope that helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download