I wrote a script for gun and projectile but whenever I fire it only fires in the right direction when im pointing upwards, if i'm pointing to the sides it shoots downwards and if i'm pointing downwards it shoots up.
I've been trying to get a simple script that makes the gun rotate to face the mouse (works) and then to spawn bullets going in the firection of the gun, however, they spawn weirdly when not facing upwards, i've tried changing the object that has the script but nothing else since i'm not exactly sure what the error is.
Gun script:
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
public float offset;
public GameObject projectile;
public Transform shotPoint;
private float timeBtwShots;
public float startTimeBtwShots;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (timeBtwShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
Projectile script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float pSpeed;
public float lifeTime;
public GameObject destroyEffect;
private void Start()
{
Invoke("DestroyProjectile", lifeTime);
}
private void Update()
{
transform.Translate(transform.up * pSpeed * Time.deltaTime);
}
void DestroyProjectile()
{
Destroy(gameObject);
}
}
I know that in the projectile script i change the transform.up inside the void update to transform.right or left the effect reverses and oly shoots correctly in the direction that I typed but I have no idead how to make it shoot properly in all directions.