代码之家  ›  专栏  ›  技术社区  ›  Zhou Haibo

统一:游戏对象第一次按键盘右箭头时不能向右移动

  •  0
  • Zhou Haibo  · 技术社区  · 6 年前

    更新:

    书中说:

    “现在,如果你在你的牌和你的玩家角色上使用框对撞机,你可能会发现 你偶尔会被一些你应该做的事情困住,你的角色可能会停止移动并紧逼 稀薄的空气。问题通常发生在紧密定位的瓷砖之间的顶点,不幸的是, 如果你确实遇到这个问题,只需尝试使用一个多边形对撞机为Squarey自己,改变 通过单击“编辑碰撞器”,然后在轮廓中创建一个小凹凸(如图5-9所示),使其稍微成形 你可以越过这些想象中的障碍。”

    在一本书之后,我使用Unity2D创建了一个简单的游戏 GameObject 名为“Player”,可以做一些简单的动作,按下时向左/向右/跳跃 / 向右箭头 / 空间 我的电脑钥匙。还有一些瓷砖作为平台地面。

    我发现一个问题,当玩游戏时,首先玩家会掉到平台上,然后当我按下 向右箭头 键或 空间 ,玩家将向左或跳,然后 单击将生效。。。

    这个问题花了我好几个小时! Freeze Rotation 下的选项 RigidBody2D ,然后右移成功了,但我还不知道为什么。

    Issue1_000

    Issue1_001

    这是我的密码,伙计们,谢谢你们的帮助!

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class Player : MonoBehaviour
    {
    
        public Rigidbody2D rb;
        public int moveSpeed;
        public int jumppower;
        public Transform groundCheck;
        public float groundCheckRadius;
        public LayerMask whatIsGround;
        private bool onGround;
    
    
        // Use this for initialization
        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }
    
        private void FixedUpdate()
        {
            onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius,
                whatIsGround);
        }
    
        // Update is called once per frame
        void Update()
        {
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
            }
    
            if (Input.GetKey(KeyCode.Space) && onGround)
            {
                rb.velocity = new Vector2(rb.velocity.x, jumppower);
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Zhou Haibo    6 年前

    好吧,让我结束这个问题。在移动过程中,玩家偶尔会停下来,这是因为对撞机的局限性。 解决方法是使用多边形碰撞器,而不是改变形状,这就是书中所说的。