c# - 统一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);
}
}
解决方案
您的问题是您绕过了 Unity 的物理引擎并直接更改了玩家的位置和旋转。Unity 的物理检查是围绕 Rigidbody 组件的使用而构建的,并且具有用于更改对象位置和旋转的几个特定功能,以便它与场景中的其他对象正确碰撞。对于您上面的用法,我将查看以下两个用于更改角色位置和旋转的函数:
https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html https://docs.unity3d.com/ScriptReference/Rigidbody.MoveRotation.html
推荐阅读
- python - Twitter API searchtweets 模块出错 - result_stream_args=premium_search_args
- reporting-services - 如何计算 ssrs 报告中 2 个数据集中的 2 个字段的百分比
- python - Pandas Dataframe Boxplot Y 轴比例不正确
- postgresql - 删除一列 postgres 说它不存在
- javascript - jQuery 验证没有 http:// 的 URL
- python - 训练多个模型:ValueError:变量 hidden1/kernel 已存在,不允许
- uglifyjs - 可以使用 terser-js cli 在配置文件中传递输入文件吗?
- javascript - Highcharts.js 问题:是否可以始终将图表的某些部分保留在可见区域中,即使设置了“overscoll”选项
- java - Java - 解密:javax.crypto.BadPaddingException
- python - 获取由标签索引的图像的像素值