- Home /
What is a good way to keep an object in front of the player?
I want to simulate loading and shooting an arrow. I would like to make it so that while the player is holding down the fire button, an arrow appears and stays in the center of the camera. I've done all this except I can't get the arrow to stay with the player, it spawns and stays there instead of move with the player. Here is my code:
public class BowScript : MonoBehaviour {
private float charge;
public float chargeMax;
public float chargeRate;
public KeyCode fireButton;
public Transform spawn;
public Rigidbody arrowObject;
private bool arrowReady = false;
private Rigidbody arrow;
void loadArrow() {
charge += Time.deltaTime * chargeRate;
if (!arrowReady) {//if there is no arrow ready
arrowReady = true;//now there's an arrow
arrow = Instantiate (arrowObject, spawn.position, Quaternion.identity) as Rigidbody;//puts an arrow in the bow spot
this.arrow.position = spawn.position;
this.arrow.isKinematic = true;
}
}
void fireArrow() {
arrowReady = false;
if (arrow != null) {
arrow.isKinematic = false;
arrow.AddForce (spawn.forward * charge, ForceMode.Impulse);//adds force to the arrow all at once
}
charge = 0;
}
void Update() {
if (Input.GetKey (fireButton) && charge < chargeMax) {//pulling the arrow back
loadArrow ();
}
if (Input.GetKeyUp (fireButton)) {//fire the arrow
fireArrow ();
}
}
}
If anyone has any suggestions I would be very appreciative, thanks
Answer by Desoro · Oct 31, 2017 at 07:57 PM
Simply just parent the arrow to the player/bow after you Instantiate it and un-parent after it is fired.
Your answer
![](https://koobas.hobune.stream/wayback/20220612142303im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Move an object toward an angle in 2d space 0 Answers
Trying to rotate child independently of parent... 0 Answers
Object rotation 2 Answers
Double reference to waypoints in FSM 0 Answers