最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - The knockback feature of my 2d fighting game isn't working - Stack Overflow

programmeradmin2浏览0评论

I have isolated the movement code and the knockback code because the issue seems to be a conflict between the two.

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.InputSystem;

public class TestMove : MonoBehaviour
{
    public float horizontal;
    public float speed = 8f;
    public bool canMove;
    public bool isFacingRight = true;
    public Rigidbody2D rb;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        canMove = true;
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Flip();

        if (Input.GetKey(KeyCode.A)) {
            horizontal = -1;
        }
        else if (Input.GetKey(KeyCode.D)) {
            horizontal = 1;
        }
        if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D))
        {
            horizontal = 0;
        }
    }
    
    private void FixedUpdate()
    {
        if (canMove) {
            rb.linearVelocity = new Vector2(horizontal, rb.linearVelocity.y) * speed;
        }
    }

    private void Flip()
    {
        if ((isFacingRight && horizontal > 0f || !isFacingRight && horizontal < 0f) && canMove)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }

    public void HitDone()
    {
        canMove = true;
    }

    public void OnTriggerEnter2D(Collider2D col) {
        if (col.tag == "ForcePunch") {
            canMove = false;
            Invoke("HitDone", 0.6f);
            rb.AddForce(transform.up * 100);
            rb.AddForce(transform.forward * 300);
        }
    }
}

I have tried changing how the inputs are gathered and using rb.linearVelocity.x * horizontal to get the movement along the X axis, but at this point, I've tried a lot and don't know what to do

发布评论

评论列表(0)

  1. 暂无评论