Knaus Irina
Knaus Irina

Reputation: 799

Raycast in angle direction

In unity3d I raycast from player forward. But I want also raycast some angle from forward. I try this

var dir = this.transform.TransformDirection(new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle)));
Physics.Raycast(this.transform.position, -dir, out hit, 9999);

But get wrong result.

Upvotes: 0

Views: 6671

Answers (1)

Neven Ignjic
Neven Ignjic

Reputation: 679

Take in mind that by using TransformDirection value of direction that will be raycasted in is compared to transform the script is attached to. If you set angle to zero it will shoot raycast in forward direction of transform the script is attached to. If you want to make the raycast independent of where the transform is facing just do dir like this:

var dir = new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));

Also take in mind in what unit your angle is? Mathf.Sin and Mathf.Cos take in angle value in radians, if you want use angles in degrees (0, 90, 180, 270) you need to convert them to radians before calculating Sin and Cos. To do this just multiply if with Rad/Deg value like this:

angle = angle * Mathf.Deg2Rad;

And do the rest like before. To help you more I need you to provide more info (test results, what you want more specific...).

Upvotes: 4

Related Questions