Hello,
I’m new to programming and Unity and have recently started my first project.
The player controlls a sphere that is being pushed forward by a forward force. The sphere is rolling along a very long cube which serves as a track.
In the beginning it works, but at a certain point the sphere appears to go forward and backward at the same time. The rotation of the sphere indicates forward movement but in relation to the track it seems to go backwards at the same time.
I´ve uploaded a video of the problem on YouTube, since it’s a bit hard to describe:
Code that’s moving the sphere:
public class MovePlayer : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
private bool isJumping = false;
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
if (isJumping == false)
{
rb.AddForce(new Vector3(0, 4, 0), ForceMode.Impulse);
isJumping = true;
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Track")
{
isJumping = false;
}
}
}
I’m not even sure if it is a physics problem or if I’ve just forgotten something, but maybe you can help?
My guess is that your suffering from an aliasing artifact:
The texture on the box is repetitive, you’re going on very high speeds and you have a limited framerate. Velocity multiplied by frame delta time is the distance travelled between two frames. If this travelled distance is close to the tiling distance of your ground texture, you get the impression that the floor is not moving, moving slow or moving backwards. This effect appears everywhere when two frequencies meet that are close to each other: in your case the frequency of moved distance and the frequency of the floor texture.
The same thing happens with the rotating sphere. If there is a full rotation between two frames, you just see the sphere in the same pose as in the frame before.
there is no direct approach overcome this. Some ideas though:
Limit the velocity
Use larger texture or increase its scale
Put large objects near the track that don’t repeat. A mountain here, a tower there.
Just a side note: don’t multiply the force by Time.deltaTime. A force is a time-independent magnitude. Once the force is applied, the physics engine applies it to the rigidbody accordingly to the current physics time step. That multiplication will provide different physics behaviors if you modify the fixed timestep later in the project.