问题描述
我一直在尝试使用我能找到的几乎所有方法(甚至使用可怕的transform.translate)来使它工作,但我似乎无法使其工作。这只是代码的草稿,如果还有其他方法可以解决,那么我想更改一些内容。
目前,他几乎不动(看起来好像以某种方式被卡在地板上。)我对使用刚体移动物体还很陌生,所以我对如何解决这个问题几乎一无所知。>
这是我最近破解的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTest : MonoBehavIoUr
{
public float speed = 10.0f;
public Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("w"))
{
movement = new Vector3(Input.GetAxis("Horizontal"),0.0f,Input.GetAxis("Vertical"));
}
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector3 direction)
{
rb.MovePosition(transform.position + (transform.forward * speed * Time.deltaTime));
}
}
解决方法
在代码中,您的moveCharacter函数位于Update函数中,其中包含的是固定的,现在应该可以使用。在未调用FixedUpdate之前,您的moveCharacter函数还不太好,并且GameObject也没有移动。
- 编辑1:您还应同时沿运动方向相乘,并更新脚本以使其适合
- 编辑2:我放错了大括号,现在就解决了
- 编辑3:您还应该每帧更新运动Vector3,而不是如果按下W键,则再次修复脚本。
- 编辑4:修复了移动错误(由于我更改了更多行,因此复制并粘贴了整个脚本)
这是更新的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTest : MonoBehaviour
{
public float speed = 10.0f;
public Rigidbody rb;
public Vector3 movement;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
movement = new Vector3(Input.GetAxis("Horizontal"),1f,Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector3 direction)
{
Vector3 offset = new Vector3(movement.x * transform.position.x,movement.y * transform.position.y,movement.z * transform.position.z);
rb.MovePosition(transform.position + (offset * speed * Time.deltaTime));
}
}