- Home /
2D Attacking help
Im having problems on getting my script working and Im not sure how to make it work, I want so that when I press the Left or Right arrow the player's "Sword" child's collision gets disabled for a while and then comes back. Also that when pressed down for a really long time it would have attacked multiple times. But what my script does is that but holding down the rhythm gets really messed up and its just really out of sync, whats wrong with my script?
var Sword: Animator;
private var isLeft : boolean = false;
function Update(){
if(Input.GetKey(KeyCode.A)) {
isLeft = true;
}
if(Input.GetKey(KeyCode.D)) {
isLeft = false;
}
if (isLeft == true) {
Sword.SetBool("Left", true);
}
if (isLeft == false) {
Sword.SetBool("Left", false);
}
if (Input.GetKey(KeyCode.LeftArrow)){
Attack();
}
if (Input.GetKey(KeyCode.RightArrow)){
Attack();
}
}
function Attack(){
gameObject.collider2D.enabled = true;
yield WaitForSeconds(1.0);{
gameObject.collider2D.enabled = false;
}
}
Answer by Professor Snake · Dec 21, 2014 at 07:49 PM
WaitForSeconds is not ideal for this purpose since you can't really "reset" it. It will just execute what's after it after x seconds, regardless of everything else. Use a timer instead, like this:
var swordTimer:float;
function Attack(){
swordTimer=Time.timeSinceLevelLoad+1.0;
}
function Update(){
if(swordTimer>Time.timeSinceLevelLoad)
gameObject.collider2D.enabled = true;
else
gameObject.collider2D.enabled = false;
}
I think I got it working, could you explain how it works? So that I can improve it better and for other scripts in the future
Time.timeSinceLevelLoad is the time that passed since the level is loaded, measured in seconds. If we assign a value of Time.timeSinceLevelLoad+1 to a variable, it means that variable>Time.timeSinceLevelLoad will return true for up to one second after it's set to that value. Calling it a timer might have been misleading.
Your answer
Follow this Question
Related Questions
Different results between "ContactPoint" and "ContactPoint2D" 0 Answers
Having problems with 2d collision triggers (javascript) 1 Answer
Collision with renderer.enabled? 0 Answers
Collide detection with tag [JS] 0 Answers
2D Collision 1 Answer