- Home /
Bullets based on mouse location
I'm playing with making a geometry wars esque game, and I'm getting the bullets to shoot towards the cursor. However, I've been playing with some code and I can't manage to get the bullets to ignore the z-axis when firing. As of current, the bullets will travel towards the z-axis and the moment they reach the world bounds, they will destroy themselves. Which is a tad annoying when you click halfway on the screen and the bullet stops at that point instead of travelling the whole distance.
I've left out the collision detectors on World Bounds, as its not needed here. Any help is appreciated.
private var bulletSpeed : Number = 10;
private var bulletDir : Vector3;
private var targetPos : Vector3;
function OnEnable()
{
// Find the position of the mouse
targetPos = Camera.main.ScreenToWorldPoint( Vector3( Input.mousePosition.x , Input.mousePosition.y , -Camera.main.transform.position.z ));
// Determine the direction towards the target
bulletDir = Vector3.Normalize( targetPos - this.transform.position );
}
function Update()
{
// Move the bullet
this.transform.Translate( bulletDir * bulletSpeed * Time.deltaTime );
}
function OnDisable()
{
// Reset movement data
this.rigidbody.velocity = Vector3.zero;
this.transform.position = Vector3.zero;
this.transform.rotation = Quaternion.identity;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612133053im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Create sprite in place of cursor that has 'lag' on it? 0 Answers
Bullet isn't moving forward 1 Answer
AddForce is not working 1 Answer
Collsions problem 0 Answers
An opinion on a bullet code 1 Answer