【问题标题】:Unity 2D character keeps playing walking animation when colliding and raycasts don't work as expectedUnity 2D 角色在碰撞时继续播放行走动画,光线投射无法按预期工作
【发布时间】:2023-02-07 03:48:17
【问题描述】:

我一直在研究一个 2d 自上而下的 rpg 游戏,我添加了行走动画等,我想阻止玩家在撞墙时做行走动画,目前我有一个带有射线投射的盒子对撞机,射线投射最初在向下行走时撞到播放器盒碰撞器,但在使用图层蒙版后它已经停止,但是在左右行走时完美地工作时出现两个我似乎无法解决的问题。首先,当向上或向下走到位于碰撞层上的瓦片地图时(这个瓦片地图有瓦片地图碰撞器,它会阻止玩家穿过它们)动画仍然播放,其次,玩家只会碰撞一次而不是碰撞时重复两个瓷砖背靠背放置时的瓷砖地图,这是我的碰撞代码,用于碰撞的瓷砖在第 6 层。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public float moveSpeed;
    private Animator ani;
    private bool isMoving;
    private Vector2 lastMove;
    private Rigidbody2D body;
    private Vector2 movement;
    private LayerMask wallLayer = 1 << 6;
    // Start is called before the first frame update
    void Start()
    {
        body = GetComponent<Rigidbody2D>();
        ani = GetComponent<Animator>();
        movement = Vector2.zero;
        isMoving = false;

    }

    // Update is called once per frame
    void Update() {
        isMoving = false;
        movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        RaycastHit2D ray = Physics2D.Raycast(body.position, movement, 0.6f, wallLayer);
    
        if((movement.x != 0f || movement.y != 0f) && !(ray && ray.collider.tag == "wall")) {
            isMoving = true;
            lastMove = movement;
        }

        ani.SetFloat("MoveX", movement.x);
        ani.SetFloat("MoveY", movement.y);
        ani.SetFloat("LastX", lastMove.x);
        ani.SetFloat("LastY", lastMove.y);
        ani.SetBool("IsMoving", isMoving);
    } 

    void FixedUpdate() {
       body.MovePosition(body.position + movement * moveSpeed * Time.deltaTime);
    }
}

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    代码看起来不错。问题很可能出在您对 AnimatorController 的配置上。

    您是否有(例如)从步行动画回到空闲状态的过渡?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-14
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多