- Home /
C# Trying to make a laser beam ability using raycast
Im trying to make a laser beam ability and thought that I could use a rapid firing raycast to achieve that. So I tried to use a coroutine to make it shoot more than just one ray after it cast. But it is shooting the rays but all from the position of the first one. Where as I need the following rays to follow the players position and not be fixed to where it was originally cast. So that the player character can actually aim and control the ability.
Any help will be greatly appreciated Thanks heaps! Also its my first post so sorry if I messed anything up
public class BeamAttack : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public Transform firePoint;
private float fireRate = 5f;
private float cooldown = 0f;
private float abilityTime = 3f;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire2") && Time.time >= cooldown)
{
cooldown = Time.time + fireRate;
Debug.Log("Cooldown time is " + cooldown);
Debug.Log("Fired");
Cast();
}
}
void Cast()
{
RaycastHit hit;
Debug.DrawLine(firePoint.position, firePoint.forward * range, Color.red, abilityTime);
if (Physics.Raycast(firePoint.position, firePoint.forward, out hit, range))
{
Debug.Log("Raycast hit this thing " + hit.transform.name);
}
StartCoroutine("WaitAndExecute");
Invoke("StopExecution", 3f);
}
void StopExecution()
{
Debug.Log("Ability pause done");
StopCoroutine("WaitAndExecute");
}
IEnumerator WaitAndExecute()
{
print("Printed after wait time");
yield return new WaitForSeconds(abilityTime);
}
}
Answer by Bunny83 · Jul 22, 2019 at 11:51 AM
Your raycasting looks fine, however your line drawing is wrong:
Debug.DrawLine(firePoint.position, firePoint.forward * range, Color.red, abilityTime);
DrawLine expects two world space positions however you feed it one worldspace position and a direction vector.
You have two options:
Use Debug.DrawRay instead. It takes a position and a direction
Use DrawLine but add the direction to the original position to get an actual endpoint:
DrawRay:
Debug.DrawRay(firePoint.position, firePoint.forward * range, Color.red, abilityTime);
DrawLine:
Debug.DrawLine(firePoint.position, firePoint.position + firePoint.forward * range, Color.red, abilityTime);
ps: Your coroutine is completely useless. What is it supposed to do?
Its ment to make it shoot more rays after the initial cast, in which it seems to do but it stays in the same position as the original ray ins$$anonymous$$d of following the firepoint
You could use
Invoke (method, time)
ins$$anonymous$$d if you need a timer for that.
Your answer
![](https://koobas.hobune.stream/wayback/20220612205305im_/https://answers.unity.com/themes/thub/images/avi.jpg)