- Home /
Shooting at mousePosition
I'm stumped; what I'm trying to do is shoot in the direction of my mouse cursor, after searching through code; I couldn't quite find the answer; this is my attempt:
if (Input.GetButton ("Fire1")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var distance: float =14;
var hitPoint : Vector3;
if (Physics.Raycast (ray, distance)) {
hitPoint = ray.GetPoint(distance);
var direction : Vector3 = hitPoint - transform.position;
Instantiate (enemyBullet, transform.position, transform.rotation);
enemyBullet.transform.position =(direction * speed * Time.deltaTime);
}
}
The bullet spawns fine; but has ain't moving; that's where I could do with some help as I am kind of lostagain!
Thanks for any suggestions, Bobble
Answer by Doireth · Jan 26, 2013 at 10:05 PM
Your script only moves the bullet a small distance in that frame. You need to have a script attached to the bullet to make it move every frame. Such as
transform.position += direction * speed * Time.deltaTime;
Though moving a transform directly like that means it will not calculate collisions correctly. Instead, attach a rigidbody to the bullet and move using
bulletRigidbody.AddForce(direction * speed);
Check out http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html for information about getting collision information. The line "Note that collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached." is important for your needs.
So; I've made progress I went by what you suggested and came up with the following:
however the bullets seem to be shooting at an angle and not along the x,y plane as such. Any ideas on how I can tweak it so that the bullets shoot straight and not at an angle?
if (Input.GetButton ("Fire1")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var distance: float =12;
var hitPoint : Vector3;
if (Physics.Raycast (ray, distance)) {
hitPoint = ray.GetPoint(distance);
var direction : Vector3 = hitPoint - transform.position;
var bullet = Instantiate(enemyBullet, transform.position, transform.rotation);
bullet.rigidbody.velocity = direction * speed;
}
}
Thanks for any suggestions!
You should never modify velocity directly as it can lead to weird results from the physics engine (see http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-velocity.html).