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);
}
}
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!
This code is essentially a splits up
Transform.Translateequivalent. This is necessary, so that the clamp can be applied at the right time.Translateworks 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 thenewXposition.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
clampedXposis legal, we can finally teleport the transform to the right spot. For this we need to pass the 3 axis as a new vector.clampedXposfor the x-axis and the transforms old positions for the y and z-axis.