chelnok
1
Hi,
trying to make bouncing laser. I found few examples using Vector3.Reflect, but cant get it work like i thought it would. I think there is something i cant understand or see anymore, or perhaps Reflect is not ment to be used like this:
function Update ()
{
drawLaser(transform.position,3);
}
function drawLaser(startPoint:Vector3,n:int)
{
var hit : RaycastHit;
var rayDir:Vector3 = transform.TransformDirection (Vector3.forward);
for(var i = 0; i < n; i++)
{
if (Physics.Raycast (startPoint, rayDir, hit, 1000))
{
Debug.DrawLine (startPoint, hit.point);
rayDir = Vector3.Reflect(startPoint, hit.normal) ;
startPoint = hit.point;
}
}
}
And here is a picture (white line by code, green one from my mind):

The Vector3.Reflect doesn’t give you a direction, but a position at the opposite of the orginal vector. So the function is more like a “Set position” for a mirror effect rather than making a laser bounce of a wall.
You have to make your own bounce calculation, which shouldn’t be too hard.
For instance:
If the laser bounces of something that is not a floor, then switch the x and/or z direction to the opposite. If the laser hits something that is a floor, change the y direction (if you would want to).
Good luck!
chelnok
3
Found my error after reading (again) other answers, and just staring the code… Here is the correct code:
function drawLaser(startPoint:Vector3,n:int)
{
var hit : RaycastHit;
var rayDir:Vector3 = transform.TransformDirection (Vector3.forward);
for(var i = 0; i < n; i++)
{
if (Physics.Raycast (startPoint, rayDir, hit, 1000))
{
Debug.DrawLine (startPoint, hit.point);
rayDir = Vector3.Reflect( (hit.point - startPoint).normalized, hit.normal ) ;
startPoint = hit.point;
}
}
}
test84
4
Why did you normalize the result?
chelnok
5
well that was just a test, but i wanted to use the result later as direction vector, like:
transform.rigidbody.velocity = rayDir * speed;
Dunno how to use code in comment (code,pre doesnt work…) , so i put this as an answer.
Here is my bouncing lazer script:
var speed:int = 333;
private var prevPoint:Vector3;
private var rayDir:Vector3;
function Start ()
{
prevPoint = transform.position;
transform.rigidbody.velocity = transform.forward *speed;
}
function OnCollisionEnter (col : Collision)
{
rayDir = Vector3.Reflect( (col.contacts[0].point - prevPoint).normalized, col.contacts[0].normal ) ;
transform.rigidbody.velocity = rayDir * speed;
prevPoint = col.contacts[0].point;
}