I am trying to make a point-and-shoot code for a 2D top-down game and the code has no errors that Unity is noticing, but when I click, the projectile that is supposed to shoot towards the mouse pointer it just stands still.
Any help with figuring this out is much appreciated.
Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointAndShootV2 : MonoBehaviour
{
public GameObject spawnPoint;
public GameObject projectTilePrefab;
public float projectTileSpeed = 1;
DateTime lastSpawnTime = DateTime.Now;
public int millisecondsBetweenProjectiles = 1;
public bool AutoFire = false;
public float secondsBeforeProjectileDies = 10;
public float secondsBeforeShotEffectsDestroy = 1;
public float Shots = 1;
public float ShotsLeft;
public float reloadTime = 1000;
private Camera cam;
[SerializeField] private float _rotationSpeed = 1;
public GameObject shotEffectsPrefab;
Rigidbody2D rb;
void Start()
{
cam = Camera.main;
rb = GetComponent<Rigidbody2D>();
ShotsLeft = Shots;
}
void Update()
{
var mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0;
var dir = mousePosition - transform.position;
transform.up = Vector3.MoveTowards(transform.up, dir, _rotationSpeed * Time.deltaTime);
if ((AutoFire || Input.GetMouseButtonDown(0)) && (DateTime.Now-lastSpawnTime).TotalMilliseconds > millisecondsBetweenProjectiles && ShotsLeft >= 1)
{
Instantiate(projectTilePrefab, spawnPoint.transform.position, spawnPoint.transform.rotation);
projectTilePrefab.GetComponent<Rigidbody2D>().AddForce(rb.velocity = new Vector2(transform.localScale.x * projectTileSpeed, transform.localScale.y * projectTileSpeed));
ShotsLeft = ShotsLeft - 1;
if (shotEffectsPrefab != null)
{
GameObject image = Instantiate(shotEffectsPrefab, spawnPoint.transform);
Destroy(image, secondsBeforeShotEffectsDestroy);
}
}
if(ShotsLeft < Shots && (DateTime.Now-lastSpawnTime).TotalMilliseconds > reloadTime)
{
ShotsLeft = ShotsLeft + 1;
}
}
}