- Home /
Drawing a line in front of player weapon
I trying to draw a line from a the nozzle of a gun to a position which is a set distance away from the gun. This line is supposed to indicate the distance projectiles can travel to. I should act similarly to a laser pointer but with a very distinct indicator to show how far the projectile can travel before being destroyed/ turned inactive and placed into an object cache/etc.
I've created a simple script to test this line out using Raycast, which uses a RaycastHit variable to set the position of the indicator. However, the indicator sticks to surfaces the raycast has hit; it does not move in front of the gun as I intended.
Here is the specific block of code I'm having issue with:
void ShowDestinationLine() {
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0)); ;
RaycastHit hit = new RaycastHit();
bool foundHit = false;
//travelDestination = transform.position + Vector3(transform.position.x, trasnform.position.y, transform.position.z + travelDist);
if (Physics.Raycast(ray, out hit, travelDist))
{
foundHit = true;
}
else
foundHit = false;
if (foundHit)
{
travelLine.SetPosition(0, transform.position);
travelLine.SetPosition(1, hit.point);
destinationMarker.transform.position = hit.point;
//cube.rotation = Quaternion.LookRotation(hitInUse.normal); //normal sets object rotation to be away from hit rotation
}
}
In this case, I'm not sure where to place the indicator (called "destinationMarker" in code) in relation to raycast.
If anyone has any idea where to place the indicator, I would appreciate any push in the right direction.
I intend to improve the functionality of the line, so if the raycast hits a surface that is a shorter distance than the specified distance for the ray to extend, the indicator shows up at that hit point, instead. I'm not sure if the initial solution will automatically solve this problem, so I have placed this reminder for myself here.
How are you calling this function? You should re-call it whenever the player moves.