首页 > 解决方案 > 统一3D。对撞机不对模型做出反应

问题描述

我使用这段代码来移动和旋转我的对象,但它会穿过墙壁。是的,我在对象和墙壁上有碰撞器,但我的对象不会与这些墙壁发生碰撞。

using UnityEngine;
using System.Collections;

public class player_Control : MonoBehaviour {
    public float upspeed;
    public float downspeed;
    public float rotationSpeed;
    Transform myTrans;
    Vector3 myPos;
    Vector3 myRot;
    float angle;

    void Start() {
        myPos = transform.position;
        myRot = transform.rotation.eulerAngles;
    }
    void FixedUpdate() { 
        angle = transform.eulerAngles.magnitude * Mathf.Deg2Rad;

        if (Input.GetKey(KeyCode.RightArrow)) { // ROTATE RIGHT
            myRot.z -= rotationSpeed;
        }
        if (Input.GetKey(KeyCode.LeftArrow)) { // ROTATE LEFT
            myRot.z += rotationSpeed;
        }
        if (Input.GetKey(KeyCode.UpArrow)) { // UP
            myPos.y += (Mathf.Cos(-angle) * upspeed) * Time.deltaTime;
            myPos.x += (Mathf.Sin(-angle) * upspeed) * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.DownArrow)) { // DOWN
            myPos.y += (Mathf.Cos(-angle) * -downspeed) * Time.deltaTime;
            myPos.x += (Mathf.Sin(-angle) * -downspeed) * Time.deltaTime;
        }
        transform.position = myPos;
        transform.rotation = Quaternion.Euler(myRot);

    }
}

标签: c#unity3d

解决方案


您的问题是您绕过了 Unity 的物理引擎并直接更改了玩家的位置和旋转。Unity 的物理检查是围绕 Rigidbody 组件的使用而构建的,并且具有用于更改对象位置和旋转的几个特定功能,以便它与场景中的其他对象正确碰撞。对于您上面的用法,我将查看以下两个用于更改角色位置和旋转的函数:

https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html


推荐阅读