I’m trying to findout what’s the best way about creating a simple casting system that can be interrupted if the player moves. So if the player casts a spell and it takes 4 seconds to cast, the player must remain still or else the spell will be cancelled. If the player stands in place for 4 seconds then spell will be casted.
I know how to create cooldown timers using time but am unsure how to completely cancel the spell mid cast if the player moves. Any help would be amazing.
what you can do is create a variable that tracks the players position every frame, and gets reassigned very frame, and check to see if the differ, something like this:
private Vector3 lastPosition;
void Update () {
if (lastPosition != transform.position) {
//player moved
}
lastPosition == transform.position;
}
I can easily convert it to Java. I’m still not sure how I would instantly cancel a specific cast. Like if I started a cast that goes for 4 seconds and it’s been 2 seconds how would I stop the casting timer and display in log at the exact time say spell cancelled ( player moved ).
Changed the code up a little. It doesn’t like the lastPosition variable for some reason, says not set to an instance of an object. If I remove the vector3 from the variable, the spell will be casted after 4 seconds but can’t be interrupted.
var castDuration : float = 4.0;
var castTime : float = 0.0;
var casting : boolean = false;
var lastPosition : Vector3;
function Update () {
if(Input.GetKeyDown("7")) {
casting = true;
}
if (casting) {
if (lastPosition != transform.Position) {
casting = false;
castTime = 0;
Debug.Log("spell cancelled");
}
lastPosition = transform.Position;
if (castTime < castDuration) {
castTime += Time.deltaTime;
}
else {
Debug.Log("casted the spell");
//casting code goes here
casting = false;
castTime = 0;
}
}
}
also, make sure that you have “lastPosition = transform.position;” in the same if statement where casting is se to true, where its checking if the player pressed 7