- Home /
How to set maximum distance for a player going left and right?
I have a player model that goes left and right with the arrow keys in front of the camera. I would like to set a Maximum Distance for the left and right side so the player doesn't go outside of the camera's view.
Help would be appreciated :)
Answer by RyanAtEvno · Mar 30, 2018 at 01:57 AM
Does the camera position move? and does the player move a specific distance each time?
The Player is moving forward at the same speed as the camera but the camera does not follow the player as it goes left and right.
I used this script in a project a year or so ago. Ignore the stuff you don't need but here. It assumes you want to kind of "switch lanes" left and right. Like an infinite runner maybe.`public class LaneSW : $$anonymous$$onoBehaviour {
public AudioSource tickSource;
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
public int laneNumber = 0;
public int lanesCount = 4;
bool didChangeLastFrame = false;
public float laneDistance = 2;
public float firstLaneXPos = 0;
public float deadZone = 0.1f;
public float sideSpeed = 5;
void Start()
{
tickSource = GetComponent<AudioSource> ();
}
void Update()
{
//Access the objects Character Controller
CharacterController controller = GetComponent<CharacterController>();
float input = Input.GetAxis("Horizontal");
//$$anonymous$$ake sure the object is grounded before doing the math for lane changes
if (controller.isGrounded)
if($$anonymous$$athf.Abs(input) > deadZone) {
if(!didChangeLastFrame) {
didChangeLastFrame = true; //Prevent overshooting lanes
laneNumber += $$anonymous$$athf.RoundToInt($$anonymous$$athf.Sign(input));
if(laneNumber < 0) laneNumber = 0;
else if(laneNumber >= lanesCount) laneNumber = lanesCount - 1;
}
}
else
{
didChangeLastFrame = false;
moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
Vector3 pos = transform.position;
pos.x = $$anonymous$$athf.Lerp(pos.x, firstLaneXPos + laneDistance * laneNumber, Time.deltaTime * sideSpeed);
transform.position = pos;
moveDirection.y -= gravity * Time.deltaTime;
controller.$$anonymous$$ove (moveDirection * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
tickSource.Play ();
other.gameObject.SetActive (false);
}
}
} `
Could you please point out which part stops the player from going off the camera?