In my game, I have two problems:
- When my character attacks while moving, he continues to move while the punch animation plays.
- I don’t know where to start with coding a combo attack.
I need it so that my character remains still after pressing the attack button and that I can perform a quick three-punch combo.
Here’s my code.
public float playerSpeed, jumpForce;
public bool grounded = false;
private bool attacking;
public Transform groundedEnd;
Animator anim;
void Start(){
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
PlayerMove ();
Raycasting ();
attackInput ();
}
void FixedUpdate(){
handleAttacks ();
resetValues ();
}
//attacking
private void handleAttacks (){
if (attacking) {
anim.SetTrigger ("first_punch");
}
}
//attack inputs
private void attackInput(){
if(Input.GetKeyDown(KeyCode.Q)){
attacking = true;
}
}
//player movement function
void PlayerMove (){
anim.SetFloat ("speed", Mathf.Abs(Input.GetAxisRaw("Horizontal")));
//move right
if(Input.GetAxisRaw ("Horizontal") > 0){
transform.Translate(Vector3.right * playerSpeed * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 0);
}
//move left
if(Input.GetAxisRaw ("Horizontal") < 0){
transform.Translate(Vector3.right * playerSpeed * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 180);
}
//jump
if(Input.GetKeyDown (KeyCode.Space) && (grounded == true)){
GetComponent<Rigidbody2D> ().AddForce (Vector2.up * jumpForce);
}
}
//check if player is grounded
void Raycasting(){
Debug.DrawLine (this.transform.position, groundedEnd.position, Color.green);
grounded = Physics2D.Linecast (this.transform.position, groundedEnd.position, 1 << LayerMask.NameToLayer("Ground"));
}
private void resetValues(){
attacking = false;
}
}