How to shoot a laser beam in a 2.5d game
So I have a laser beam thats working just fine in a 2.5d action game, where the camera is facing the character (like super mario bros) however when I click my mouse to shoot the beam it only shoots in the direction that the camera is pointing. It also only shoots at gorund level and not any higher as well as its not emitting from the player even though the script is attached to the player object. I want it to shoot to wherever I click the mouse (be it in the x,y, or z axis) and have the laser beam emit from the player. I know the issue is the camera.main and the fact that im using raycast as I don't want to raycast from the camera however I don't know what to change to make it execute the way i'd like it to. Heres the code:
public class RayGun : MonoBehaviour { public float shootRate; private float m_shootRateTimeStamp;
public GameObject m_shotPrefab;
RaycastHit hit;
float range = 1000.0f;
void Update()
{
if (Input.GetMouseButton(0))
{
if (Time.time > m_shootRateTimeStamp)
{
shootRay();
m_shootRateTimeStamp = Time.time + shootRate;
}
}
}
void shootRay()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, range))
{
GameObject laser = GameObject.Instantiate(m_shotPrefab, transform.position, transform.rotation) as GameObject;
laser.GetComponent<ShotBehavior>().setTarget(hit.point);
GameObject.Destroy(laser, 2f);
}
}
}
Your answer
Follow this Question
Related Questions
Bouncing laser, wierd flickering 0 Answers
How to make a Laser projector like shown. 1 Answer
How to make laser stay with player while moving 1 Answer
Calculating laser energy 1 Answer