- Home /
Instantiating a prefab/bullet and sending it to my mouse position??
First off, brand new to Unity. It's awesome and so much fun to play around with, but I'm so lost.
Ok, so, I have a top-down, 2-d shooter where I have a character (sphere, for now) that shoots smaller spheres (bullets.)
The game is in the x,z plane, as in the y isn't needed because it's a 2-d game. Now I've been looking for a way to be able to add force to my instantiated bullets, so they travel TOWARD my mouse position. I've been doin' a little searching and doctoring and stuff, but I fear I've dug myself into a hole. Now my script looks like this:
var prefabBullet:Transform;
var shootForce:float = 500;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
var myPos = transform.position;
var dist = Camera.main.transform.position.y - myPos.y;
var x = Input.mousePosition.x;
var z = Input.mousePosition.z;
var dir = Camera.main.ScreenToWorldPoint(Vector3(x, dist, z)) - myPos; var BulletClone = Instantiate(prefabBullet, myPos, Quaternion.LookRotation(dir));
BulletClone.rigidbody.velocity = dir.normalized * shootForce;
Physics.IgnoreCollision(BulletClone.collider, collider);
Destroy(BulletClone,5); //<-- ignore this, i'll fix it later. focus on the top part
}
}
Now the problem is, when I click ("Fire1"), the prefabs instantiate and then just chill in space. They don't have any force added to them or launch in any way. Both them and my player gameobject have rigidbodies. Use Gravity is checked off on the bullet prefab. The only thing I could think of is if they get caught in the player gameobject's rigidbody and then just chill in space. If this is the case then how would I fix that? Instantiate it TOWARD mouse position before adding force toward mouse position? I have a feeling i'm on the right track (but maybe not).
Thanks in advance for your help! :D
Your answer
Follow this Question
Related Questions
Writing weapon imprecision 1 Answer
2D Top down shooter, gun is shaking while moving and Cursor solutions 0 Answers
How to make LineRenderer in GameObject Facing? 1 Answer
Creating a wrap around bullet effect like Asteroids. 1 Answer
How to make it so enemies only move towards the player when the player is colliding with an object 1 Answer