- Home /
Bullets follow mouse after shooting in Sidescroller
So as the title states, my bullets continue to follow the mouse around after I soot instead of going in a straight line. So if I move the mouse left, the bullets curve left. This would be great for a homing missile, but I'm not there right now. How do I store the position of the mouse so the bullet only goes to the stored position and not the new one? Here's my code so far to both calculate the mouse position and fire the bullet towards it.
Finding mouse Position Followed by firing towards mouse:
// this creates a horizontal plane passing through this object's center
var plane = Plane(transform.position, Vector3.up);
// create a ray from the mousePosition
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// plane.Raycast returns the distance from the ray start to the hit point
var distance: float;
if (plane.Raycast(ray, distance)){
// some point of the plane was hit - get its coordinates
hitPoint = ray.GetPoint(distance);
hitPoint.z = -19;
}
direction = hitPoint - transform.position;
// Firing bullet towards mouse
transform.Translate(direction bulletSpeed Time.deltaTime)
Answer by Piflik · May 14, 2012 at 02:17 PM
You have this script on the bullets?
I would add the script your aircraft/spaceship/whatever. Once you have calculated the direction, instantiate a new bullet that faces this direction. The bullet itself just needs a script to move forward.
I actually calculate the distance on the PlayerScript, and call it in the BulletScript. Here's how I instantiate the bullet in the player script: var instantiatedbullet = Instantiate(bullet,GameObject.Find("SpawnPoint").transform.position, transform.rotation);
The spawn point rotates to face the mouse at all times as well.
Edit: Use the direction in Start() or Awake() only. $$anonymous$$ove the bullet only forward in Update().
Or instantiate the bullet with 'direction.normalized' ins$$anonymous$$d of 'transform.rotation' (and again just move it forward).
When I add the direction.normalized ins$$anonymous$$d of the transform.rotation when I instantiate the bullet, I just get the following error:
BCE0023: No appropriate version of 'UnityEngine.Object.Instantiate' for the argument list '(UnityEngine.Transform, UnityEngine.Vector3, UnityEngine.Vector3)' was found.
Oh, right...instantiate needs a quaternion, not eulerAngles...
Quaternion.Euler(direction.normalized) should work...
That fixed the error, but not the problem. I've posted a video on youtube that will hopefully help solve this problem. You can find it here and if you need any code, just ask.
Here's the link: http://youtu.be/tT09CA-pY9$$anonymous$$