How can I move a RigidBody object smoothly between 3 possible positions?
I'm new to Unity. I'm building a game where my primary object controlled by the player is a car that can move between 3 lanes (Left, Center, and Right). I followed a couple tutorials and found that the resulting positions were never consistent in the movement. Because of the scale of my environment I need left, center and right lanes to be located at -.18, 0 and .18. With my current code I'm struggling to control where the player ends up when the user hits the key to move left or right.
The idea I've been pursuing is that when the user hits moveL button it would start moving left by changing the horizVel. Then this movement should be stopped in the coroutine after .2 seconds and adjusted accordingly to the specific position it should be in.
rigidBody = GetComponent<Rigidbody> ();
if ((Input.GetKeyDown (moveL)) && (horizLaneNum>1)&& (controlLocked == "n"))
{
horizVel = -1;
StartCoroutine (stopSlideSideHoriz ());
horizLaneNum -= 1;
controlLocked = "y";
}
IEnumerator stopSlideSideHoriz()
{
yield return new WaitForSeconds (.2f);
horizVel = 0;
if (rigidBody.position.x > -0.08 && rigidBody.position.x < 0.09) {
rigidBody.MovePosition(new Vector3(0.0f, rigidBody.position.y, rigidBody.position.z));
};
if (rigidBody.position.x > 0.09) {
rigidBody.MovePosition(new Vector3(0.18f, rigidBody.position.y, rigidBody.position.z));
};
if (rigidBody.position.x < -0.08) {
rigidBody.MovePosition(new Vector3(-.18f, rigidBody.position.y, rigidBody.position.z));
};
controlLocked = "n";
Debug.Log(string.Format("x position: {0}", rigidBody.position.x));
}
I expected from the code above that as long as the user position was within range of the correct position the rigidBody.movePosition command would move it to the exact position before the coroutine ends.
With my debug log, everything numbers-wise looks correct, but in Unity I can see that my player position is never ending up where it should be. Its always off and sometimes by a little bit and other times by a lot.
What am I missing? Is there a better way to do this?
Your answer
Follow this Question
Related Questions
Everything that moves need an Rigid Body? 1 Answer
Realistic Soccer Ball Dribbling? 1 Answer
[Help] Player stops moving when hitting wall diagonally 0 Answers
Movement is inconsistent 0 Answers
Objects slowly move by their own? 1 Answer