User error.
Issue with shooting projectiles in the direction of the arrow keys
I'm trying to make a small shooter "Binding of Isaac" kind of game and I'm attempting to use the arrow keys to shoot a projectile object. My issue is that I can shoot LEFT and RIGHT perfectly fine but no force is added for the Z axis when shooting UP and DOWN.
if (Input.GetKey (KeyCode.RightArrow) && Time.time > nextFire) {
//Instantiate (prefab, new Vector3 (playerBody.transform.position.x + 1f, 0.5f, playerBody.transform.position.z), playerBody.rotation);
GameObject projectile = Instantiate (prefab, new Vector3 (playerBody.transform.position.x + 1f, 0.5f, playerBody.transform.position.z), playerBody.rotation);
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(1000, 0));
nextFire = Time.time + fireRate;
}
if (Input.GetKey (KeyCode.LeftArrow) && Time.time > nextFire) {
GameObject projectile = Instantiate (prefab, new Vector3 (playerBody.transform.position.x - 1f, 0.5f, playerBody.transform.position.z), playerBody.rotation);
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(-1000, 0));
nextFire = Time.time + fireRate;
}
if (Input.GetKey (KeyCode.UpArrow) && Time.time > nextFire) {
Instantiate (prefab, new Vector3 (playerBody.transform.position.x, 0.5f, playerBody.transform.position.z + 1f), playerBody.rotation);
GameObject projectile = Instantiate (prefab, new Vector3 (playerBody.transform.position.x, 0.5f, playerBody.transform.position.z + 1f), playerBody.rotation);
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(0, 0, 1000));
nextFire = Time.time + fireRate;
}
if (Input.GetKey (KeyCode.DownArrow) && Time.time > nextFire) {
GameObject projectile = Instantiate (prefab, new Vector3 (playerBody.transform.position.x, 0.5f, playerBody.transform.position.z - 1f), playerBody.rotation);
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(0, 0, -1000));
nextFire = Time.time + fireRate;
}
I really don't see where the issue lies. Any ideas?
EDIT: I just realised that I froze the projectiles Z axis movement instead of Y which is what I had originally intended). The AddForce was working fine.
Answer by TheGreyRaveen · Dec 27, 2016 at 05:52 PM
if I'm correct, when you shoot projectile UP and DOWN it has to fly on Y axis, not Z. For example you should have
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(0, -1000, 0));
instead of
projectile.GetComponent<Rigidbody> ().AddForce (new Vector3(0, 0, -1000));
The Y axis is up, for some reason. I had this idea as well but the projectiles just shoot up/down towards the ceiling, not up/down along the scene.
Follow this Question
Related Questions
How to apply a force at certain point of an object? 0 Answers
how to change the velocity of a rigid body based on a forward 0 Answers
How can I move an object in the direction another object is facing. 1 Answer
Bullet shooting not working 0 Answers
Apply force to character based on thrusters attached to a hand like objects (multiple sources) 1 Answer