- Home /
Player movement boudaries in 2D
So in my game the player object is set at a fixed height from the ground and it's only able to move horizontally. I use the transform function to move so using 2D colliders doesn't work. I used the code below to set boundaries for the players horizontal movement; they work but the only problem is that when the player gets to the limit X coordinate it sticks there for a bit before being able to move the other direction. The game I'm making is based on reflexes so it would greatly impact the gameplay. Code is here below, thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private float MovementSpeed = 0.1f;
private float Xax;
private float Distance;
public Transform target;
public float MaxLeft;
public float MaxRight;
void Start () {
}
void Update () {
//Constant distance from ground
Distance = target.transform.localScale.y * 1.5f - 5;
//X axis movement input
Xax += MovementSpeed * Input.GetAxis("Horizontal");
//Vector and transform
Vector3 Movement = new Vector3(Xax, Distance, 1);
if (Movement.x > MaxRight) {
Movement.x = MaxRight;
}
if (Movement.x < MaxLeft) {
Movement.x = MaxLeft;
}
transform.position = Movement;
}
}
Answer by Jaz30 · May 15, 2018 at 11:37 PM
Hi @balzangiacomo maybe use can use Mathf.Clamp,
Check out this video, I used that method on that tutorial. This method will let you set your own min and max position of gameObject. I think this will help you. :)
https://www.youtube.com/watch?v=LGWZzSewMJI&list=PLiIYE_N6GMrbActcM22k_r0MRkLesKudF