团结2d如何阻止所有朝向对撞机的运动,以防止实体晃动

问题描述 投票:0回答:1

问题很简单:我有一个带有刚体2d的玩家和一个附着在其上的对撞机2d,并且我有一个墙壁,上面有一个碰撞器2d。当我将玩家移到墙上时,他们会发生碰撞,但是我的玩家开始非常快速地摇晃,看起来它想要穿过墙壁。

GIF:http://gph.is/2ENK3ql

我需要玩家在与墙壁碰撞时停止移动并拒绝向墙壁进一步移动而不会破坏远离墙壁的移动。

玩家移动代码:

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

public class PlayerMovement : MonoBehaviour {
// Variables
public bool moving = true;
float playerMovSpeed = 5.0f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (moving == true)
    {
        PlayerMove();
    }
    PlayerMoveCheck();
}

public void Set_moving(bool val)
{
    moving = val;
}

void PlayerMove()
{
    if (Input.GetKey(KeyCode.W))
    {
        transform.Translate(Vector3.up * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.A))
    {
        transform.Translate(Vector3.left * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.S))
    {
        transform.Translate(Vector3.down * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.D))
    {
        transform.Translate(Vector3.right * playerMovSpeed * Time.deltaTime, Space.World);
    }
}

void PlayerMoveCheck()
{
    if (Input.GetKey(KeyCode.W) != true && Input.GetKey(KeyCode.A) != true && Input.GetKey(KeyCode.S) != true && Input.GetKey(KeyCode.D) != true)
    {
        moving = false;
    }
    else
    {
        moving = true;
    }
}

提前致谢。

c# unity3d unity5
1个回答
0
投票

transform.Translate()实际上充当了你的变换的传送。这意味着你的玩家被放入新的坐标,然后发现碰撞并将其推出 - 这就是为什么你的角色在墙上“振动”的原因。相反,您应该考虑将rigidbody添加到您的播放器并使用.velocity.position或“.AddForce()”修改移动,这将在移动过程中将碰撞的物理特性带入帐户。

对于力量移动,您可以执行以下操作:

void Update()
{
    rbody.velocity = rbody.velocity * .9f; // custom friction

    if (Input.GetKey(KeyCode.W))
        rbody.AddForce(Vector2.up * speed);
    if (Input.GetKey(KeyCode.S))
        rbody.AddForce(Vector2.down * speed);
    // repeat for A and D
}
© www.soinside.com 2019 - 2024. All rights reserved.