How to restrict player movement using Mathf.Clamp()?

110 Views Asked by At

HI I am making a game where player has to control a cube. Cube moves on x axis. Using Horizontal input axis. The problem I am facing with is that I don't want the cube to go out from the screen. I tried using Mathf.Clamp() function to clamp the movement but It doesn't work.

Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControls : MonoBehaviour
{
    float xMovement;
    [SerializeField] private  float movingSpeed = 5f;
    [SerializeField] private float xRange = 5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        movement();
    }

    private void movement()
    {
        float clampedXpos = Mathf.Clamp(xMovement, -xRange, xRange);
        xMovement = Input.GetAxis("Horizontal");
        transform.Translate(clampedXpos * movingSpeed * Time.deltaTime, 0, 0);
       
    }
}

1

There are 1 best solutions below

1
Voidsay On BEST ANSWER

GetAxis returns a value in the range of -1 and 1. You clamp the previous frames xMovement between -5 and 5 not the player's global position!

private void movement()
{
  xMovement = Input.GetAxis("Horizontal");
  float newXpos = transform.position.x + xMovement * movingSpeed * Time.deltaTime;
  float clampedXpos = Mathf.Clamp(newXpos, -xRange, xRange);
  
  transform.position = new Vector3(clampedXpos, transform.position.y, transform.position.z);
}

This code is essentially a splits up Transform.Translate equivalent. This is necessary, so that the clamp can be applied at the right time.

Translate works by adding your axis delta values to the current position and "teleporting" the transform to the newly calculated spot. You already calculate the correct frame-rate independent delta, so that's just copied. Since only the x-axis is clamped we only calculate the newXposition.

Before "teleporting" the transform we need to make sure that it stays in bounds by clamping. If we assume that your previous position was 4.8f and the x-delta is 0.3f. Their sum and the newXposition would be 5.1f (which would be out of bounds), however the clamp will limit it to 5.

Being posetive that our clampedXpos is legal, we can finally teleport the transform to the right spot. For this we need to pass the 3 axis as a new vector. clampedXpos for the x-axis and the transforms old positions for the y and z-axis.