Question by
rubix1823 · Dec 17, 2020 at 10:32 PM ·
mathmoving platformmovinggameobjectmoving-platform
moving obstacle overshooting
obstacle moves between 2 declarable points but it keeps overshooting the points when i run it
using UnityEngine;
public class MovingObstacle : MonoBehaviour {
public Rigidbody rb;
public float xForce = 100f;
private double startPos;
public float offset = 10f;
bool leftMove = false;
bool rightMove = false;
// Start is called before the first frame update
void Start()
{
startPos = rb.position.x;
rightMove = true;
}
// Update is called once per frame
void Update()
{
if (rb.position.x >= (startPos + offset))
{
rightMove = false;
leftMove = true;
}
else if (rb.position.x <= (startPos - offset))
{
leftMove = false;
rightMove = true;
}
}
void FixedUpdate()
{
if (rightMove == true)
{
rb.AddForce(xForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (leftMove == true)
{
rb.AddForce(-xForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
}
Comment
Your answer
