Hi guys!
I’m trying to do a aim system where the bullet will be shot in direction of the mouse position…
I’ve tried to use Input.mousePosition, but after some researchs , I found that this is relative to pixels not to my transform.position.
I’ve seen too the Camera.main.ScreenToWorldPoint solution, but that does’nt work how I expected.In my game I instantiate the bullet at the transform.position facing the corresponding side, and after that I apply a vector as the velocity of the bullet.
Does this way of firing right or am I’m going in the wrong direction?
Thank you!
Here is a simple spawner script that, on a mouse click, shoots the ‘prefab’ at the mouse position. I had gravity scale set to 0 on the prefab.
#pragma strict
var prefab : GameObject;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
var go = Instantiate(prefab, transform.position, q);
go.rigidbody2D.AddForce(go.transform.up * 500.0);
}
}
I’m pretty new to this stuff but I think you want to use the “Normalize” method seen here. What it does it keep the direction the same but sets the magnitude to 1. Then you can take that direction * Missile speed and that will pretty much guarantee that your missile files the same speed in the correct direction no matter the pre-normalized distance