简体   繁体   English

防止2D播放器穿过墙壁

[英]Prevent 2D Player from moving through wall

I am trying to make the basics of a top down game. 我正在尝试制作自上而下游戏的基础知识。

I currently have a Player sprite that has a Kinematic RigidBody2D applied to it with a box collider 2D. 我目前有一个玩家精灵,它有一个带有盒式对撞机2D的Kinematic RigidBody2D。 The scale of this sprite is (1,1). 这个精灵的比例是(1,1)。

The wall sprite has a box collider with a scale of (20,1). 墙精灵有一个比例为(20,1)的盒子对撞机。

To control the player I am using the following code. 要控制播放器,我使用以下代码。

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


public class PlayerMovement : MonoBehaviour {
    public Rigidbody2D rb2D;
    void Start() {
        rb2D = GetComponent<Rigidbody2D>();
    }
    void FixedUpdate() {
        if (Input.GetKey (KeyCode.UpArrow)) {
            Vector2 move = new Vector2(0,1);
            rb2D.MovePosition(rb2D.position + move);
        }
        if (Input.GetKey (KeyCode.DownArrow)) {
            Vector2 move = new Vector2(0,-1);
            rb2D.MovePosition(rb2D.position + move);
        }
    }
}

With the code above I can control the Player and move them up or down, when attempting to hit the wall below the Player does not hit the wall but instead travels through it as if it was not there. 使用上面的代码,我可以控制播放器并向上或向下移动它们,当试图击中播放器下方的墙壁时没有撞到墙壁,而是穿过它,好像它不在那里。

I'm new to Unity so any other information that might be useful feel free to let me know and I'll update my question. 我是Unity的新手,所以任何其他可能有用的信息都可以随时告诉我,我会更新我的问题。

Thanks! 谢谢!

Uncheck IsKinematic property in the RigidBody2D component. 取消选中 IsKinematic在属性RigidBody2D组件。 That's because setting isKinematic to true makes your gameObject NOT get affected by any physical or gravity forces. 这是因为isKinematic设置为true,使你的gameObject 得不到受任何物理重力

And also see if your wall is not marked as IsTrigger ! 还要看看你的是不是标记为IsTrigger Check that in the Collider component of your wall . 检查墙壁的碰撞器部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM