direction of a raycast

Hi!
I simply want to make my raycast of my object go in the direction up-left, but I just can’t manage it to set it correctly. That’s my script for the direction “up”:

var transformStone = GetComponent<Transform>();
        Vector2 direction = transform.TransformDirection(Vector2.up) * 5;

        Ray2D Ray = new Ray2D(new Vector2(transformStone.position.x, transformStone.position.y + 1), direction);
        RaycastHit2D[] Hits = Physics2D.RaycastAll(Ray.origin, Ray.direction, 2);

And it works very good. But as you see I cheated a little and just put in “Vector2.up”, so how can I set the direction precise? :slight_smile:

Try Vector2 direction = transform.TransformDirection(Vector2.up+Vector2.left) * 5;.

1 Answer

1

If you want up-left in worldspace (ignoring any rotation of your object), then you don’t need TransformDirection. And since you only want the direction of the vector, there’s no need to change the magnitude either. So line 2 simply becomes:

Vector2 direction = Vector2.up + Vector2.left;

or

Vector2 direction = new Vector2(-1f, 1f);

Thanks to you, tanoshimi and Sergio7888, you both helped me very much :D