I'm doing a 2D raycast where i have to pass distance. The scenario is this:

I'm using rigidbody2d.Moveposition to move my character instantly. However, before a character is moved, i want to do a raycast in that direction. My Movement code is:

if (Input.GetKeyDown (KeyCode.D)) {

where speedx is Vector2 Vector2(1,0) (can be increased as necessary). So when A is down, first i want to do a raycast to see if it hits any collider and then move or not move the character to that position. However, i'm not able to understand how to set the raycast distance so that it corresponds to the exact distance my character intends to move.

So, what i'm looking for is a way to corelate Vector2 and float.


1 Answer 1


You can get the length of a vector (the distance from its start to end position) using vector.magnitude.

Note that typically an entity doesn't move its full speed as distance in any single frame, since d = v * t. So you'll usually want to multiply your speed or velocity by your timestep to get the distance traversed this frame.

Also, note that the amount of space your character needs clear to complete the move won't just be the span between their old and new position, but also a little extra to account for the size of the character. You might do that by adding a fudge factor to your vector's length, to account for the character's bounding radius. That only checks in the direction of movement though.

If you want to be really robust, you can use the CircleCast or BoxCast methods (SphereCast or CapsuleCast in 3D) to check whether an object with some volume to it can travel through space to the destination without hitting anything.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .