using System.Collections; using System.Collections.Generic; using UnityEngine; public…
- User
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BowAttack : MonoBehaviour { public float arrowSpeed = 1; public GameObject arrowPrefab;
Rigidbody2D rigid; void Start() { rigid = GetComponent<Rigidbody2D>(); } void Update() { //Fire when we click the mouse if (Input.GetMouseButtonDown(0)) { //Get the vector from the player to the mouse Vector3 mousePos = Input.mousePosition; mousePos.z = 10; Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos); Vector3 p2m = worldPos - transform.position; p2m.Normalize(); //Spawn a bullet GameObject go = Instantiate<GameObject>(arrowPrefab); go.transform.position = transform.position; //Shoot it in that direction Rigidbody2D arrowRigid = go.GetComponent<Rigidbody2D>(); arrowRigid.velocity = p2m * arrowSpeed; } }} make it so that the arrow can only be fired every 1 seconds
- Assistant
To implement a delay of 1 second before the arrow can be fired again, you can add a timer variable and check its value before allowing the arrow to be fired. Here's an updated version of the code:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BowAttack : MonoBehaviour { public float arrowSpeed = 1; public GameObject arrowPrefab; Rigidbody2D rigid; private float fireDelay = 1f; // Delay time in seconds private float lastFireTime; void Start() { rigid = GetComponent<Rigidbody2D>(); } void Update() { // Check if enough time has passed since the last firing if (Time.time - lastFireTime >= fireDelay) { //Fire when we click the mouse if (Input.GetMouseButtonDown(0)) { //Get the vector from the player to the mouse Vector3 mousePos = Input.mousePosition; mousePos.z = 10; Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos); Vector3 p2m = worldPos - transform.position; p2m.Normalize(); //Spawn a bullet GameObject go = Instantiate<GameObject>(arrowPrefab); go.transform.position = transform.position; //Shoot it in that direction Rigidbody2D arrowRigid = go.GetComponent<Rigidbody2D>(); arrowRigid.velocity = p2m * arrowSpeed; // Update the last firing time lastFireTime = Time.time; } } } }In this updated code, the
fireDelayvariable is set to 1 second. ThelastFireTimevariable stores the time of the last arrow firing. If enough time has passed since the last firing (Time.time - lastFireTime >= fireDelay), the arrow can be fired again. After firing, thelastFireTimeis updated to the current time (Time.time). This enforces the 1-second delay between consecutive arrow firings.