- Home /
How can i move a game object up and down so it acts like a obstacle for my sphere player
the object is a cube which has to go up and come down acting like a obstacle which requires timing to complete THANKS FOR YOUR HELP!!!!
Answer by Dragate · Oct 06, 2017 at 10:24 AM
https://docs.unity3d.com/ScriptReference/Mathf.PingPong.html
float speed = 1f;
float delta = 3f; //delta is the difference between min y to max y.
void Update() {
float y = transform.position.y + Mathf.PingPong(speed * Time.time, delta);
Vector3 pos = new Vector3(transform.position.x, y, transform.position.z);
transform.position = pos;
}
@Dragate i didnot understand the mathf.pingpong part can u help me
Just like with the ping-pong ball (in the sports game), this function will bring back and forth y's value...from 0 to delta and when it reaches delta value it will start going back to 0 and all over again. We take advantage of that in y axis to make it go up and down.
It's just like Vector3.$$anonymous$$oveTowards() @knorke suggested, but $$anonymous$$athf.PingPong() will take care of the the reverse movement as well.
sorry to bother you again but how to figure the offset @Dragate
I know that this thread has been here some time, but I have like the same problem. When I put your code in, it keeps telling me that there is an unexpected symbol ")". What is going on? Can u help me?
$$anonymous$$ade a few changes and it worked for me.
void Update() {
float y = $$anonymous$$athf.PingPong(speed * Time.time, delta);
Vector3 pos = new Vector3(transform.position.x, y, transform.position.z);
transform.position = pos;
}
adding transform.position.y was creating an infinite movement towards y+
Answer by knorke · Oct 06, 2017 at 10:17 AM
Use the MoveTowards function
transform.position = Vector3.MoveTowards(firstPosition, endPosition, speed);
Answer by wizbit · Oct 06, 2017 at 11:39 AM
Hey
you can use a Co-Routine and use Vector3.Lerp
IEnumerator move(Transform _transform)
{
startPos = _transform.position;
t = 0;
endPos = new Vector3(startPos.x + System.Math.Sign(input.x) * startPos.y = System.Math.Sign(input.y), startPos.z);
factor = 1f;
while (t < 1f)
{
t += Time.deltaTime * moveSpeed * factor;
_transform.position = Vector3.Lerp(startPos, endPos, t);
yield return null;
}
yield return 0;
}
Your answer
Follow this Question
Related Questions
gameObject moves twice? 0 Answers
Object moves to 0,0,0? (Just want to know why it works) 1 Answer
Game Object not moving in Canvas 0 Answers
How to drag a game object with a mouse (along x axis)? 1 Answer
Vector3.Lerp not working? 5 Answers