- Home /
Trying to make a bullet fire at the mouse using transform.up
I'm making a bullet hell, and I've reached the point where I want to add guns that fire multiple bullets in a spread. As you can see in the code below, after instantiating my bullets from another script, this script increments their transform every frame with the 'moveDirection' Vector3 in Update(). However, I cant create a 'spread' if they all fire towards the same location, so after doing some research it looks like it would be best to stop making the fire at a set direction and instead make the bullets always move using transfrom.up and simply alter there rotation after being instatiated. However, I have had nothing but issues trying to make this change. If amyone has any ideas on how I could begin to take what I have below and make it move using transform.up, it would be greatly apprictaed.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Projectile : MonoBehaviour {
public float bulletLife;
public float turnSpeed;
Vector3 moveDirection;
public enum bulletDirection{straight, left, right};
[HideInInspector]
public bulletDirection dir;
void Start()
{
StartCoroutine(destroyAfterTime());
if (dir == bulletDirection.straight) {
moveDirection = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
faceMouse();
} else if (dir == bulletDirection.left){
moveDirection = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
faceMouse();
} else if (dir == bulletDirection.right){
moveDirection = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position);
faceMouse();
}
moveDirection.z = 0;
moveDirection.Normalize();
}
private void Update()
{
transform.position = transform.position + moveDirection * WeaponManager.instance.currentWeapon.shootSpeed * Time.deltaTime;
}
public void faceMouse(){
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = (Camera.main.transform.position- transform.position).magnitude;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
transform.up = direction;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "wall")
{
VisualEffects.spawnHitEffect(transform);
Destroy(gameObject);
} else if (other.tag == "enemy")
{
VisualEffects.spawnHitEffect(transform);
Destroy(gameObject);
}
}
IEnumerator destroyAfterTime()
{
yield return new WaitForSeconds(bulletLife);
VisualEffects.spawnHitEffect(transform);
Destroy(gameObject);
}
}