- Home /
Question by
ghost20000 · Mar 30, 2015 at 09:24 AM ·
velocitydirectionplatformmovingmoving-platform
Cant get moving platform to go the other direction
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);
}
}
Comment
checking float values for specific values can be unreliable - try using $$anonymous$$athf.Approximately() or greater/less than.
Answer by Spinnernicholas · Mar 30, 2015 at 07:00 PM
Don't use equals("==") with floats.
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(){
transform.Translate(Direction * movespeed * Time.deltaTime);
if (transform.localPosition.x > 40.5f)
{
vector2 position = transform.localPosition;
position.x = 40.5f;
transform.localPosition = position;
Direction = -Direction;
}
if (transform.localPosition.x < 30.2f)
{
vector2 position = transform.localPosition;
position.x = 30.2f;
transform.localPosition = position;
Direction = -Direction;
}
}
}