GUN SCRIPT:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pistol : Weapon
{
private void Update()
{
if (Input.GetButtonDown(“Fire1”))
{
Shoot();
}
}
public override void Shoot()
{
//Calculate bullet direction
//Select random degrees angle between the range
float direction1 = Random.Range(-range, range);
//Transform that into radians
var rad1 = Mathf.Sin((direction1 * Mathf.PI) / 180);
//Sin(x) theorem
float B1 = Mathf.Sin(rad1);
float A1 = Mathf.Sqrt(1 - (B1 * B1));
//This is the direction the bullet will have
Vector2 lineDir1 = new Vector2(A1, B1);
//We create the bullet and apply all values
GameObject go = Instantiate(actualBullet, shot.transform.position, transform.rotation);
go.transform.localScale = transform.localScale;
Bullet b = go.GetComponent();
b.damage = damage;
b.lifeTime = bulletLife;
b.speed = bulletSpeed;
b.side = side;
b.lineDir = lineDir1;
b.bulletCollisions = bulletCollisions;
}
}
BULLET SCRIPT:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[HideInInspector]
public float damage;
[HideInInspector]
public float lifeTime;
[HideInInspector]
public float speed;
[HideInInspector]
public float side;
[HideInInspector]
public Vector2 lineDir;
[HideInInspector]
public string[ ] bulletCollisions;
public Rigidbody2D rb;
private float normalization;
private Vector3 normalizedOrientation;
private Collider2D col;
private SpriteRenderer sr;
private TrailRenderer tr;
private bool oneTime;
public float velocity = 10;
public float velX = 0f;
public float velY = 0f;
public virtual void Start()
{
oneTime = false;
rb = GetComponent();
col = GetComponent();
sr = GetComponent();
tr = GetComponent();
//Normalize the vector direction (It can be changed with lineDir = lineDir.normalized)
normalization = Mathf.Sqrt(Mathf.Pow(lineDir.x, 2) + Mathf.Pow(lineDir.y, 2));
normalizedOrientation = new Vector3(lineDir.x / normalization, lineDir.y / normalization);
}
void Update()
{
lifeTime -= Time.deltaTime;
if(lifeTime <= 0 && !oneTime)
{
FadeOut();
oneTime = true;
}
if (lifeTime <= -2)
{
Destroy(gameObject);
}
rb.velocity = new Vector2(velX * velocity, velY * velocity);
}
public virtual void FixedUpdate()
{
//Moves in the direction selected
//rb.velocity = new Vector2(side * speed * normalizedOrientation.x, normalizedOrientation.y * speed);
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D col)
{
//Collide with everything selected
foreach (string s in bulletCollisions)
{
if(col.gameObject.CompareTag(s))
{
FadeOut();
oneTime = true;
}
}
}
//Die function, but it keeps trail renderer alive till it disappears
public virtual void FadeOut()
{
col.enabled = false;
sr.enabled = false;
tr.emitting = false;
}
}
\\\\\\\\\\\\\\\\\\\
For some reason whenever i shoot the bullets always go right instead of whichever way the gun is rotated, does anyone have a solution??