- Home /
How do i scale a prefab laser to hit.distance
So i have a prefab laser and I was wondering how do i make it scale on the z axis when it hits an enemy? I want it basically like a laser pointer and stop when it hits an enemy. I have it done with a line renderer. But i want to use my laser prefab. Please help!
Using Line Renderer (Works perfectly)
LineRenderer lineRenderer = (LineRenderer)player.GetComponent(typeof(LineRenderer));
lineRenderer.useWorldSpace = false;
lineRenderer.SetVertexCount(2);
RaycastHit hit;
Physics.Raycast(transform.position,transform.forward, out hit);
if(hit.collider)
{
lineRenderer.SetPosition(1,new Vector3(0,0,hit.distance));
}
else
{
lineRenderer.SetPosition(1,new Vector3(0,0,100));
}
Using Laser Prefab (Doesnt scale properly)
RaycastHit hit;
if(Physics.Raycast(weaponSpawn.transform.position,lookPos, out hit,100F))
{
if(hit.collider.gameObject.CompareTag("Enemy"))
{
objCreatedLaser.transform.localScale = new Vector3(0,0,hit.distance);
Debug.Log("Enemy");
Debug.DrawRay (weaponSpawn.transform.position, lookPos, Color.red);
}
else
{
objCreatedLaser.transform.localScale += new Vector3(0, 0, 10F);
Debug.Log("No Enemy");
Debug.DrawRay (transform.position, lookPos, Color.blue);
}
}
Not sure what your points of reference are for scaling, but by setting the local scale x and y components, I would expect the object to not show up. Plus on line 8, you have '+=' which seems strange. So:
1) What is the natural size of the object you are scaling here. That is when the scaling is (1,1,1), how many world units does it take in the x, y, and z direction?
2) What size should the x and y be? They should not zero (unless this is a plane, in which came one of them could be zero)?
3) If this is a plane/Quad, what kind of plane/Quad are you using?
4) What is the start point to measure from? You are doing casting the ray from weaponSpawn.transform.position, but it appears that you are drawing the LineRenderer from the origin?
Answer by Gucci Gagan · Oct 20, 2013 at 10:50 PM
Well that solved most of my problems. I was seting it to 0. It was only to be set to 0 if i was adding to the localScale. This approach wasn't working very well because the hit.distance wasn't adjusting the legth(z axis) of the laser.
Im going with the line renderer approach becaues it has alot of useful methods.