John Doe
John Doe

Reputation: 29

Clamp player movement correctly

I have the following code to clamp player movement. It works but i have a problem. For example if the player is at position -3.05 and if I hold the button to move left the player still moves over the -3.05 limit to about -3.56. Once i let go of the button it bounces back to -3.05. Same goes for the right side. I do not want it to go over the limits no matter what.

Vector3 tmpPos = transform.position;
tmpPos.x = Mathf.Clamp(tmpPos.x, -3.05f, 3.05f);
transform.position = tmpPos;

The following is the way i add movement to the player:

rigidbody.AddForce (movement * speed * Time.deltaTime);

Upvotes: 1

Views: 2822

Answers (3)

John Doe
John Doe

Reputation: 29

I solved my problem. Instead of using the AddForce to move the object

rigidbody.AddForce (movement * speed * Time.deltaTime);

I use rigidbody.position to move the object. I use Mathf.Clamp to limit the movement before applying it to rigidbody.position.

Upvotes: 0

Jay Kazama
Jay Kazama

Reputation: 3277

You should not mix up transform operation with rigidbody unless it's marked isKinematic. So instead of transform.position, try clamping rigidbody.position inside of FixedUpdate.

void FixedUpdate(){
  Vector3 pos = rigidbody.position;
  pos.x = Mathf.Clamp(pos.x, minX, maxX);
  rigidbody.position = pos;
}

However, since you're using AddForce to move your object, a much simpler way is to make empty game objects with box collider on the left and right of the object, which then will limit your object movement like invisible walls.

Upvotes: 2

Qubei
Qubei

Reputation: 1069

Try using rigidbody.MovePosition(tmpPos); instead of setting transform.position.

Upvotes: 0

Related Questions