Home > Back-end >  Why is my character collision working for moving to the right, but not to the left?
Why is my character collision working for moving to the right, but not to the left?

Time:07-04

I am trying to create a boundary for my level in Unity 3d, and I do not want my character to be able to move past a certain value on the x-axis. It works for the right side, I can move right and my character doesn't go past LevelBounds.rightSide. However, for the left side, once I hit LevelBounds.leftSide, my character gets stuck and I can no longer move anymore. I am also noticing that the x position actually exceeds the LevelBounds.leftSide. Here is my update() function:

 void Update()
{
    horizontalInput = Input.GetAxis("Horizontal");
    if (this.gameObject.transform.position.x > LevelBounds.leftSide)
    {
        transform.Translate(Vector3.right * Time.deltaTime * turnSpeed * horizontalInput);
    }
    if (this.gameObject.transform.position.x > LevelBounds.rightSide)
    {
        transform.Translate(Vector3.left * Time.deltaTime * turnSpeed * horizontalInput);
    }
    player.transform.Translate(Vector3.forward * Time.deltaTime * speed);
}

CodePudding user response:

You using an input axis that ranges from -1 to 1. You should either use:

Math.Abs(horizontalInput);

or:

Vector3.right 

on both time.

  • Related