Reflect a angle for a rotation?

Hello guys,

I was wondering the best way to take a direction(raycast, point, normal) And then take the reflection of the hit normal and set another object to point that direction.

I am pretty sure I have to wrong approach. But here is the code so far:

var noHitDistance : float = 200;
var otherObject : Transform;

function Start () {
    GetComponent(LineRenderer).useWorldSpace = true;
}

function Update () {
    var render = GetComponent(LineRenderer);
    var fwd = transform.forward;
    var hit : RaycastHit;
    render.SetPosition(0, transform.position);
    if(Physics.Raycast(transform.position, fwd, hit)){
        render.SetPosition(1, hit.point);
    }
    else{
        render.SetPosition(1, transform.TransformDirection(0, 0, noHitDistance));
    }
    var hitNormal = Quaternion.FromToRotation(Vector3.up, hit.normal);

    var pos : Vector3;
    pos = Vector3.Reflect(pos, hit.normal);
    otherObject.transform.rotation = Quaternion.Euler(pos);
}

Thanks for any help!

Do you mean like a ray of light hitting a mirror (or a steel ball hitting concrete)? In that case the angle of reflection equals the angle of incidence. That means that the angle between the raycast and the surface normal should equal the angle between the direction of the other object and the surface normal. You can use axis=Vector3.Cross(ray, normal) to get an axis of rotation, and theta = Mathf.Atan2(axis.magnitude, Vector3.Dot(ray, normal)) to get the angle. Then just rotate the ray with Quaternion.AngleAxis()

–

Well, you can calculate everything on your own but Vector3.Reflect is exactly what he needs. @3dDude: I guess you wanted to reflect the fwd vector. Also you used Quaternion.Euler with a direction but Euler() needs a Vector3 that represents 3 angles. You need Quaternion.LookRotation() to create a rotation that "looks" along the direction vector.

–

Thanks all! I feel stupid now xD

–

2 Answers

2

Try setting pos before using it in reflect.

I was about to write something similar :D

–

Use LookRotation:
otherObject.transform.rotation = Quaternion.LookRotation(pos);

The 'Pos' should really be renamed to 'reflectDir' as that's what the Vector3.Reflect function returns.

–