- Home /
Question by
akashisayaki · Feb 02, 2021 at 06:20 PM ·
forceenemy aigame developmentcatapult
Reuse player's script for the enemy
Hi, I'm trying to make a catapult game here and wonder if it's possible to reuse the player's launch script for the enemy. Basically I want my enemy to have the same behaviour as the player. Just the enemy will increase force and launch automatically other than controlling it with mouse button. Here's the code:
public class EnemyLauncher : MonoBehaviour { [SerializeField] private EnemyBouncer bouncer;
public float holdDownStartTime;
private bool canLaunch = true;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Mouse Down, start holding
holdDownStartTime = Time.time;
}
if (Input.GetMouseButton(0))
{
// Mouse still down, show force
float holdDownTime = Time.time - holdDownStartTime;
bouncer.ShowForce(CalculateHoldDownForce(holdDownTime));
}
if (Input.GetMouseButtonUp(0) && canLaunch == true)
{
canLaunch = false;
// Mouse Release, Launch!
float holdDownTime = Time.time - holdDownStartTime;
bouncer.Launch(CalculateHoldDownForce(holdDownTime));
StartCoroutine(Cooldown());
}
}
IEnumerator Cooldown()
{
float holdDownTime = Time.time - holdDownStartTime;
yield return new WaitForSeconds(holdDownTime);
canLaunch = true;
}
private float CalculateHoldDownForce(float holdTime)
{
float maxForceHoldDownTime = 2f;
float holdTimeNormalized = Mathf.Clamp01(holdTime / maxForceHoldDownTime);
float force = holdTimeNormalized * Bouncer.MAX_FORCE;
return force;
}
}
Comment
Answer by davidnibi · Mar 14, 2021 at 12:25 AM
You don't need to take the player input for the enemy - just figure out a number that would attribute to force and apply it to that. The only thing you would need here is to AddForce from the enemy.
Your answer
