首页 > 解决方案 > 使用 raycast2D 并让玩家旋转到 .hit 以防止他们跳跃

问题描述

和标题所说的差不多。将此脚本添加到我的玩家角色后:

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

    public class RotateHit : MonoBehaviour
    {
        public string Tag;
        public float offset;

        private Transform target;
        private Vector3 targetPos;
        private Vector3 thisPos;
        private float angle;

        void Start()
        {
            target = GameObject.FindGameObjectWithTag(Tag).GetComponent<Transform>();
        }

        void LateUpdate()
        {
            targetPos = target.position;
            thisPos = transform.position;
            targetPos.x = targetPos.x - thisPos.x;
            targetPos.y = targetPos.y - thisPos.y;
            angle = Mathf.Atan2(targetPos.y, targetPos.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
        }

    }

每当我按下跳跃键时,音效都会播放,但它们不会移动。如果这很重要,我会尝试向rigidbody2D 增加力量以使它们跳跃。

我的跳转代码:

        if (m_Grounded && jump)
        {
            m_Grounded = false;
            m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
        }
    bool jump = false;

        if (Input.GetButtonDown("Jump"))
        {
                jump = true;
                FindObjectOfType<AudioManager>().Play("Jump");
        }

代码被拆分,因为每个部分都在不同的组件中。

标签: c#unity3d

解决方案


推荐阅读