- Home /
How to make a dynamic bow shot and the arrow to curve and turn correctly when shot?
What i mean by dynamic bow shot is that i can just use a prefab as the model and the code takes care of "animation" for how far the arrow is drawn back and power is based on that. I have a basic shooting script that will instantiate and create a raycast for collision detection. Here is the code i have for my current arrow object.
public class ArrowScript : MonoBehaviour {
// The objects transform
private Transform myTransform;
//Speed of bullet
public float arrowSpeed = 1f;
// Prevents bullet from causing further harm once it hits something
private bool expended = false;
// Casts a ray in front of bullet to see if it will hit a recognizable collider
private RaycastHit hit;
// The range of the ray currently 1.5 units in front of bullet
public float rayRange = 1.5f;
// Name of what the bullet collides with
public string colliderName = "Floor";
// Lifespan of projectile
public float expireTime = 5;
// Attaching the explosion particle effect to the script
public GameObject arrowHit;
// Use this for initialization
void Start () {
//Assigns myTransform to whatever this script is attached to's transform.
myTransform = transform;
// Initializes the co-routine (ienumerator). That way it starts when the object is created
StartCoroutine(DestroyMyselfAfterSomeTime());
}
// Update is called once per frame
void Update () {
// Makes it move in the up direction (y) times bulletspeed and it is smoothed out by Delta time, keeps it at a constant speed.
myTransform.Translate(Vector3.up * arrowSpeed * Time.deltaTime);
// If the ray hits something and expended is false
if(Physics.Raycast(myTransform.position, myTransform.up, out hit, rayRange) && !expended) {
// If what the bullets collides with has the tag...
if(hit.transform.tag == colliderName) {
// Instantiate the bullet hit
Instantiate(arrowHit, hit.point, Quaternion.identity);
expended = true;
arrowSpeed = 0;
//Make the bullet stop rendering
//myTransform.renderer.enabled = false;
//Logs to make sure it has been called
}
}
// Draws a line
Debug.DrawRay(myTransform.position, myTransform.up, Color.red);
}
IEnumerator DestroyMyselfAfterSomeTime() {
// Waits for 5 seconds then continues on in code
yield return new WaitForSeconds(expireTime);
Destroy(myTransform.gameObject);
}
}
So overall i want to create a bow system that will shoot proportional to how far it is drawn back. I also want the arrow to have a weight and fall towards the ground realistically, possibly using rigid bodies. When i was tinkering with it, the arrow would not rotate with the right torque and i tried adding some via the constant force component.
Thank you for all the help!
Sincerely, Dibes
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Configurable Joints pass through colliders 2 Answers
Add force problem 1 Answer
Rotate rigidbody over time 2 Answers
Rotating an Arrow 2 Answers