我遇到的問題是當我全速運行(即按下 a 和 w 并向右看 45 度時,它不會故意使用 .normalized)撞到墻壁或其他任何允許玩家穿過它的東西,所以我的代碼是
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 moveDirection = m_Input;
moveDirection = transform.TransformDirection(moveDirection);
rb.MovePosition(transform.position moveDirection * moveSpeed);
并moveSpeed設定為0.2。我已經檢查過了,所有的對撞機都不是觸發器。任何幫助將不勝感激
uj5u.com熱心網友回復:
首先做雙重檢查
- 你所有的對撞機和剛體都是 3d
- 一切都在同一層上(或者您的層設定為相互互動)
- 您的剛體與您的??對撞機連接到同一個游戲物件
但是,您的問題似乎是您rigidbody的設定為運動學(因為Rigidbody.MovePosition僅供運動學剛體使用)
如果您rigidbody設定為,kinematic則不會對您的物件施加任何力(例如對撞機法向力),因此它將能夠穿過墻壁。
解決方案
避免這種情況的最簡單方法是確保將剛體設定為非運動學,然后通過Rigidbody.velocity.
類似于:
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0,
Input.GetAxis("Vertical"));
Vector3 moveDirection = m_Input;
moveDirection = transform.TransformDirection(moveDirection);
rb.velocity = (moveDirection * moveSpeed);
這應該根據物理移動您的角色,并允許與對撞機進行正確的互動。
此外,您應該知道,如果您確實想要移動這樣的剛體,您應該確保這樣做FixedUpdate并按Time.FixedDeltaTime.
uj5u.com熱心網友回復:
現在跳轉被打破了這是完整的腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPSMovement : MonoBehaviour
{
public Rigidbody rb;
public GameObject cam;
Vector2 rotation = Vector2.zero;
public float sensitivity = 10f;
public string xAxis = "Mouse X";
public string yAxis = "Mouse Y";
public float OmoveSpeed;
public float SprintSpeed;
public float moveSpeed;
public float jumpVar;
public bool Grounded = false;
public Vector3 slideScale;
public Vector3 normalScale;
public Vector3 dir;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
moveSpeed = OmoveSpeed;
slideScale = new Vector3(1, 0.5f, 1);
normalScale = new Vector3(1, 1, 1);
}
// Update is called once per frame
void FixedUpdate()
{
dir = rb.velocity;
// Should be cross platform movement
Vector3 m_Input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 moveDirection = m_Input;
moveDirection = transform.TransformDirection(moveDirection);
rb.velocity = (moveDirection * moveSpeed);
// Sprinting
if (Input.GetKey(KeyCode.LeftControl))
{
moveSpeed = SprintSpeed;
}
else
{
moveSpeed = OmoveSpeed;
}
// Jumping
if (Input.GetKey(KeyCode.Space))
{
if (Grounded)
{
rb.velocity = new Vector3(0, jumpVar, 0);
Grounded = false;
}
}
// TO-DO: Sliding
// Camera Rotation
rotation.x = Input.GetAxis(xAxis) * sensitivity;
rotation.y = Input.GetAxis(yAxis) * sensitivity;
rotation.y = Mathf.Clamp(rotation.y, -90, 90);
var xQuat = Quaternion.AngleAxis(rotation.x, Vector3.up);
var yQuat = Quaternion.AngleAxis(rotation.y, Vector3.left);
transform.localRotation = xQuat;
cam.transform.localRotation = yQuat;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "Ground")
{
Grounded = true;
}
}
private void OnCollisionExit(Collision collision)
{
Grounded = false;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442260.html
上一篇:批量重命名檔案C#
