- Home /
Firing projectiles on the XZ Plane
Greetings,
I am trying to fire an arrow from my character. I am on the XZ plane. I am targeting towards the mouse.
Right now the Arrow goes in the right direction but immediately burrows into the ground... Any ideas?
if(Input.GetMouseButtonDown(0))
{
GameObject bullet = (GameObject) Instantiate(objBullet, transform.position, objBullet.transform.rotation);
bullet.transform.LookAt(new Vector3(mousePosition.x, transform.position.y, mousePosition.z));
bullet.transform.GetComponent<Rigidbody>().AddForce(bullet.transform.forward.normalized*50);
}
Have you tried adding a higher multiplier than 50 to your AddForce method? Also, you don't need to normalize the forward vector as it already is normalized.
It hits the ground because gravity is working on it. Ins$$anonymous$$d of using physics to move the arrow, I would add a script to it and move it with transform.Translate
.
The script would look like this:
void Update () {
transform.Translate (0, 0, 5 * Time.deltaTime); // replace the 5 with your value. This would mean that the arrow moves 5 units per second.
}
The script goes on the arrow prefab.
I have tried doing it without gravity, but it results in the same thing... It seems that the issue is in the LookAt function on the arrow since Unity doesn't work well with tracking the mousePosition on the XZ plane... Apparently even if I put the LookAt(mousePos.x,0,mousePos.z) it will get a y value... Not sure why....
@cjdev I had the multiplier at 1000 I just lowered it so I could see what was happening. I tried to normalise it since the arrow speed was higher if the mouse was further away... Normalize didn't fix the issue...
Answer by thegunslinger19 · Sep 08, 2015 at 01:38 PM
If you want physic based movement, disable gravity on rigidbody.
Answer by Wolfdog · Sep 08, 2015 at 06:05 PM
I believe that this is a problem with how you are spawning your bullet. Replace this line:
GameObject bullet = (GameObject) Instantiate(objBullet, transform.position, objBullet.transform.rotation);
with this:
GameObject bullet = (GameObject) Instantiate(objBullet, new Vector3 (transform.position.x, transform.position.y + 1, transform.position.z), Quaternion.identity);
If your character's piviot point is on the ground, then you were spawning the bullet also on the ground. Doing it the way I just did, will spawn the bullet 1 meter above the ground.