So i wrote a script to shoot arrows using a bow (fps) , and it’s as simple as a gun + bullet and stuff like that.
Here’s my script :
using UnityEngine;
using System.Collections;
public class ArrowShoot : MonoBehaviour {
public int Ammo=0;
public PlayerManager PlayerManager;
public Animator HandsAnim;
public bool Shooting=false;
public GameObject ArrowGO; // The prefab i want to instantiate
public GameObject DefaultArrow; // This is the arrow that shows in the game (and moves whenever the bow moves , it's attached to the bow) ... it's a child for the Player
// Use this for initialization
void Start () {
PlayerManager = GetComponent<PlayerManager> ();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0) && HandsAnim.GetBool("AimingBow") && !Shooting && Ammo > 0) {
Shoot ();
} else if (Input.GetMouseButtonUp (0) && Shooting) {
Shooting = false;
}
}
void Shoot(){
Vector3 position = DefaultArrow.transform.position;
Quaternion rotation = DefaultArrow.transform.rotation;
Shooting = true;
Ammo--;
GameObject Arrow = Instantiate (ArrowGO, position, rotation)as GameObject;
Arrow.GetComponent<Rigidbody> ().AddForce (transform.forward * 10);
}
}
The problem is whenever i shoot the arrow it stays the same place and doesn’t really shoot forward.
Any help is greatly appreciated!
The script seems alright, I guess the only problem is in line 35. Take a look at the documentation of AddForce. You can define the mode in which the force is added. In Your Case I suggest ForceMode.VelocityChange. So the line would look like this:
Other than that, it may happen that the position you are spawning the arrow might collide with the playerPosition… So maybe move the spawning position or make sure that the physics layers do not collide (Physics manager).
That definitely got it moving thanks for that! , but now it only shoots for the same position no matter what …do you think you know what the problem might be?
Yup, the problem there is in line 28 / 29. The Default arrow defines where the object is spawned. You could either use transform.position instead or something like transform.position + transform.forward * offset to spawn the arrow a bit further away from the player.
As for the quaternion rotation (Line 29) you should probably use the tranform information as well. Start with transform.rotation and see if you need to do any other changes.