- Home /
The question is answered, right answer was accepted
Can't get platform to move to the other direction
This is my code:
using UnityEngine;
using System.Collections;
public class MovingPlat : MonoBehaviour {
public static float movespeed = 2f;
public Vector2 Direction = Vector2.right;
public void Start(){
}
public void Update(){
if (transform.localPosition.x == 40.5f)
Direction = -Direction;
if (transform.localPosition.x == 30.2f)
Direction = Vector2.right;
transform.Translate(Direction * movespeed * Time.deltaTime);
}
}
Answer by lordlycastle · Mar 29, 2015 at 09:58 PM
Well yeah, I doubt that the x of the position of the transform is exactly 40.5 any time, unless set by you from code. Use a range, like position.x < 41 && position.x > 40
so it never changes direction and the default value of Direction
is .right
so it only moves in right.
Thanks! although now my character doesn't stay on the platform
Answer by supernat · Mar 29, 2015 at 09:59 PM
Your localPosition.x value will never equal 40.5f. Floating point values are not exact, so what you call 40.5, a floating point register may store as 40.49999934. And the other problem is that you are not adding 1 bit of precision to the register every frame, so you'll almost never even hit this number. You'd have to get very lucky for moveSpeed * Time.deltaTime to = 40.49999934 in the first place.
The solution is to check using >= (for the 40.5 case) and <= (for the 30.2 case) if that works for you. Or check localPosition.x is within 2.0 units of 40.5 (in other words >= 39.5 and <= 41.5). But in the latter case, you had better be sure that moveSpeed*Time.deltaTime will never be greater than 2.0 units in any single frame (you'd need to add code and add some hysteresis, say make sure it's never greater than 1.9), or you'll miss that window when they minimize the game or some other hiccup causes a delay making Time.deltaTime bigger than you expected.
Follow this Question
Related Questions
Cant get moving platform to go the other direction 1 Answer
Moving Platform Moves instantly. 1 Answer
Rigidbody on a platform 2 Answers
Moving Platform Troubles 0 Answers
Multiplayer - Other players shaking back and fourth on moving platform 2 Answers