I’m new to Unity, and I’m writing a script to move a player game object between one of three locations.
The Center of the three locations is at origin (0,0,0), and the other two locations are found at (-2,0,0) and (2,0,0).
My player begins in the center and I’m able to translate my player game object from left to right without moving past the 2 and -2 positions, thanks to clamping the player movement. However, I’m unable to make the player game object stop precisely at origin.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public float speed;
public Boundary boundary;
public KeyCode moveL;
public KeyCode moveR;
public float horizVel = 0;
public int laneNum = 2;
public string controlLocked = "n";
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
GetComponent<Rigidbody>().velocity = new Vector3 (horizVel, 0, 0);
if ((Input.GetKeyDown (moveL)) && (laneNum > 1) && (controlLocked == "n"))
{
horizVel = -10;
laneNum -= 1;
controlLocked = "y";
}
if ((Input.GetKeyDown (moveR)) && (laneNum < 3) && (controlLocked == "n"))
{
horizVel = 10;
laneNum += 1;
controlLocked = "y";
}
}
void FixedUpdate()
{
rb.position = new Vector3
(Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 0.0f, 0.0f);
}
First of all, you’re mixing Update with FixedUpdate. Since you’re working with the rigidbody’s velocity, you should be using FixedUpdate exclusively.
Secondly, you’re changing it before reading input, which is kind of the wrong order.
And finally, instead of clamping the final position, you should clamp the vector by which the velocity is changed to reach the target you’re trying to reach. This way, you’ll be able to reach every intermediate position.