- Home /
Trouble with implementing Vector2.ClampMagnitude in the Rigidbody2D.MovePosition function
Hi there,
So I basically have a square in my scene that has a Kinematic Rigidbody2D component added to it that I can move with the left and right arrow keys on my keyboard via the MovePosition function but I want it to collide flush against a wall like shown in this video here: https://youtu.be/4VFgIHQdxZk?t=1
I've tried to write the following code with the Vector2.ClampMagnitude function which you can see in this screenshot: https://ibb.co/mFM99Pb
But this code gives me an error. Basically what I'm trying to say in this code is that if the raycast that is shooting from the square hits the wall then the value of velocity can only be between 0 and the value of hit.distance. This means that when raycast hits the wall the player can continue travelling towards the wall at the same speed that it was before the raycast detection and then when hit.distance equals zero the square will stop flush against the wall.
However when I try to run this code I get this error in the console "No overload for method "ClampMagnitude" takes 3 arguments".
I'm just wondering could someone advise me on what I'm doing wrong?
Answer by DenisIsDenis · May 29, 2021 at 05:30 AM
In the ClampMagnitude function, only the vector and its maximum length are needed:
Vector2.ClampMagnitude(velocity, distance);
Thanks for this.
If I'm writing the following code:
moveInput = Input.GetAxisRaw("Horizontal");
Vector2 velocity = Vector2.right * (moveInput * speed);
if (hit) {
velocity = Vector2.ClampMagnitude(velocity, hit.distance);
}
What am I actually saying with the ClampMagnitude function? Am I saying that if the raycast has hit something then velocity will equal to (1,0) or (-1,0) until hit.distance equals zero at which point velocity will equal (0,0)?
To stop the player at a distance from the wall, we need to modify the code a bit:
if (hit) {
float distance = 1.3f;
velocity = Vector2.ClampMagnitude(velocity, hit.distance - distance);
}
Your answer
Follow this Question
Related Questions
2D Colliders stops working at random despite rigidbody, OnMouseDown not called 0 Answers
Blocking a kinematic rigid body2D through collision with static and/or other kinematic object? 2 Answers
2D Pixel Art Player Blurry/Vibrates When Moving Via Kinematic Platformer Controller 1 Answer
[SOLVED] What is the best way to move my rigidbody car in unity? 1 Answer
How do I make a rigidbody2d that doesn't do anything on collision? 1 Answer