I have been working on a trying to implement a simple shooting system but I have no idea how the bullet prefab on instantiating changes its rotation and moves in a different direction as it should.
I also tried to manually change the transform and rotation of the instantiated projectile but even that did not work .
Here is the shoot class that instantiates projectiles from the weapon
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoot : MonoBehaviour {
public float Offset=-90;
public GameObject projectile;
public Transform ShotPos;
public float timeBtwShots;
public float startTimeBtwShots;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 5.23f;
Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
if(timeBtwShots<=0)
{
if(Input.GetMouseButtonDown(0))
{
Instantiate(projectile,ShotPos.position,transform.rotation);
projectile.transform.position=ShotPos.position;
projectile.transform.rotation=transform.rotation;
timeBtwShots=startTimeBtwShots;
}
}
else{
timeBtwShots-=Time.deltaTime;
}
}
}
And this is the projectile class that destroys projectiles and translates its position
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
public float bulletSpeed=7;
public float lifeTime=1f;
private Vector3 Target;
// Use this for initialization
void Start () {
Invoke("DestroyProjectile",lifeTime);
//Target=Camera.main.ScreenToWorldPoint(Input.mousePosition)+Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
// Update is called once per frame
void Update () {
transform.Translate(Vector2.up*bulletSpeed*Time.deltaTime);
}
void DestroyProjectile()
{
Destroy(gameObject);
}
}