I am making a 2D shooter game similar to Metal Slugs I guess. I want the mouse to control the aim direction.
I accomplished this well by instantiating bullets towards the screen to world position of the mouse. My only problem now is the velocity of the bullet changes depending on the distance of the mouse from the character.
I am trying to figure out the simplest way to do this and would greatly appreciate any insight. I am guessing I need to use the angle between the mouse position and the character, and magnitude to create a new vector.
// Gun Control Code
using UnityEngine;
using System.Collections;
public class GunContLookAt : MonoBehaviour {
public GameObject barrel;
public Vector3 pubMousePos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 mousePos2 = new Vector3(mousePos.x, mousePos.y, barrel.transform.position.z);
Vector3 test = new Vector3(barrel.transform.position.x * 2, barrel.transform.position.y * 2, barrel.transform.position.z);
Debug.DrawLine(barrel.transform.position, test);
pubMousePos = mousePos2;
barrel.transform.LookAt(mousePos2);
}
}
// Shoot Code
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
private GunContLookAt gunCLA;
public GameObject gunPivot;
public GameObject gunPos;
public GameObject barrel;
public Rigidbody ammo;
public float vel = 10;
// Use this for initialization
void Start () {
gunCLA = gunPivot.GetComponent<GunContLookAt>();
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.I))
{
Debug.Log("Position = " + barrel.transform.position + "
Local Position is = " + barrel.transform.localPosition);
}
if(Input.GetButton("Fire1"))
{
Rigidbody clone;
clone = Instantiate(ammo, barrel.transform.position, barrel.transform.rotation)as Rigidbody;
Vector3 targDir = gunCLA.pubMousePos;
Vector3 forward = gunPos.transform.forward;
float angle = Vector3.Angle(targDir, forward);
clone.velocity = transform.TransformDirection((gunCLA.pubMousePos - barrel.transform.position) * vel).normalized;
}
}
}