Queee
1
Hey im making a 2d top down shooter and i just found out how to make my character shoot but he only shoots in one direction how do i make him shoot where my mouse is at?
Heres my code
Shooting:
using UnityEngine;
using System.Collections;
public class PlayerShooting : MonoBehaviour {
public Vector3 bulletOffset = new Vector3(0, 0.5f, 0);
public GameObject bulletPrefab;
int bulletLayer;
public float fireDelay = 0.25f;
float cooldownTimer = 0;
void Start() {
bulletLayer = gameObject.layer;
}
// Update is called once per frame
void Update () {
cooldownTimer -= Time.deltaTime;
if( Input.GetButton("Fire1") && cooldownTimer <= 0 ) {
// SHOOT!
cooldownTimer = fireDelay;
Vector3 offset = transform.rotation * bulletOffset;
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position + offset, transform.rotation);
bulletGO.layer = bulletLayer;
}
}
}
oStaiko
2
What you’ll want here is to calculate the angle between the x axis, and the line made by the two points being your character and the mouse. The vector math behind this looks like this:
GameObject player;
Camera camera; //You need to set up your main camera here
float nextFire = 0;
void Update ()
{
if (Input.GetButtomDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireDelay;
Vector2 characterPos = camera.WorldToScreenPoint(player.transform.position);
Vector2 mousePos = Input.mousePosition;
Vector2 xAxis = new Vector2 (0,1); //Represents direction of X-axis
Vector2 newLine = new Vector2(mousePos.x-characterPos.x, mousePos.y-characterPos.y);
float angle = Vector2.Angle(xAxis, newLine);
Quaternion rotation = Quaternion.identity;
rotation.eulerAngles = new Vector3(0, angle, 0); //Assuming it's top down, with only y rotations
Gameobject obj = (GameObject) Instantiate(bulletPrefab, transform.position, rotation);
obj.layer = bulletLayer;
}
}