using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovment : MonoBehaviour
{
private CharacterController Controller;
public float speed = 12f;
public float gravity = -9.81f * 2;
public float JumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
bool isMoving;
private Vector3 lastPosition = new Vector3(0f,0f,0f);
void Start()
{
Controller = GetComponent<CharacterController>();
}
void Update()
{
//Karakter yere değiyormu.
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
Debug.Log("Birim karedeki hız: " + Controller.velocity.magnitude);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
Controller.Move(move*speed*Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y += Mathf.Sqrt(JumpHeight * -2f * gravity);
}
velocity.y += gravity*Time.deltaTime;
Controller.Move(velocity*Time.deltaTime);
if(lastPosition != gameObject.transform.position && isGrounded == true)
{
isMoving = true;
}
else
{
isMoving = false;
}
}
}
我正在尝试制作一个FPS游戏,上面的代码是角色的移动代码,但是角色在斜行时会加速。出现此问题的原因是,当角色尝试向两个方向移动、同时沿对角线或其他方向移动时,角色的速度会增加?另外,我如何测量角色的速度,即每单位帧的移动速度。游戏引擎统一
这不是一个完美的解决方案,但已经相当不错了。
Vector2 inVector = new Vector2(Input.GetAxis("水平"), Input.GetAxis("垂直"));
if(inVector.magnitude > 1) { inVector.Normalize(); }
Vector3 移动 = 变换.right * inVector.x + 变换.forward * inVector.y;