Hi folks,
I’ve got a small 2D project going to help me learn Unity and C#. I have no previous experience, and have only been at this a few weeks so please be patient
Here’s where I’m up to and what I’m trying to accomplish.
I have a player object, and a laser prefab.
I’ve got the code sorted to instantiate the laser prefab and fire it off to the right. This continues then destroys itself when it’s out of scene. It works fine.
What I want to do however, is change this so that the laser is fire in the direction the mouse is pointing when it’s fired. I’ve googled a few different phrases and looked at a few different results that came up, but none of it makes any sense to me I’m afraid!
I’ve have a Player script that controls that, and a Laser script. Here’s what’s in both of them.
If anyone knows of a tutorial, or guide, or can give me some guidance on how to accomplish what I’m trying to do that would be extremely helpful. Thanks.
Player Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField]
private float fireRate = 0.1f;
// fire rate variable
private float canFire = 0.0f;
// checks if the time has passed to allow firing again - prevents spamming fire
[SerializeField]
private GameObject _laserPrefab;
[SerializeField]
private float speed = 6.0f;
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(0, -2.0f, 0);
}
// Update is called once per frame
void Update()
{
Movement();
if (Input.GetMouseButtonDown(0))
{
shoot();
}
}
private void Movement()
{
float horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * speed * horizontalInput * Time.deltaTime);
}
private void shoot()
{
if (Time.time > canFire)
{
Instantiate(_laserPrefab, transform.position + new Vector3(1, 0, 0), Quaternion.identity);
}
canFire = Time.time + fireRate;
}
}
Laser
```csharp
**using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Laser : MonoBehaviour
{
[SerializeField]
private float _speed = 10.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.right * _speed * Time.deltaTime);
// destroy laser object when it goes out of screen
if (transform.position.x >= 10.0f)
{
if (transform.parent != null)
{
Destroy(transform.parent.gameObject);
}
Destroy(this.gameObject);
}
}
}**
```