Я создал игрока в Unity, добавил к нему компонент твердого тела и реализовал эффект движения, но фактический эффект при движении заставил меня чувствовать себя немного дергающимся и не таким плавным (по сравнению с использованием Transform). Как добиться эффекта плавного движения?
Демонстрационное видео «Трансформирование»
Демонстрационное видео «Rigidbody»
Вот все соответствующие коды для управления движением персонажа:
using UnityEngine;
using UnityEngine.EventSystems;
public class Common
{
// Detect tilt status
public bool isTilted(Transform trans, float toleranceAngle)
{
return Vector3.Angle(trans.up, Vector3.up) > toleranceAngle;
}
}
public class MoveControl
{
public Vector3 GetMoveValue(Vector3 direction, float speed)
{
return speed * direction * Time.deltaTime;
}
public void MoveDirectly(Transform trans, Vector3 direction, float speed)
{
trans.Translate(GetMoveValue(direction, speed));
}
public void Jump(Rigidbody rb, float jumpForce)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
public void MoveForRigidbody(Rigidbody rb, Vector3 direction, float speed)
{
// Using Vector3.Lerp for smooth interpolation and reducing roughness in physical simulations
Vector3 newPosition = rb.position + direction * speed * Time.fixedDeltaTime;
rb.MovePosition(Vector3.Lerp(rb.position, newPosition, speed * Time.fixedDeltaTime));
}
}
public class PlayerControl : MonoBehaviour
{
public float speed = 15f; // Move speed
// Instantiate common script
private Common common = new();
private MoveControl moveControl = new();
private Rigidbody playerRigidbody;
// other logic
// Ground objects used for jump height detection
public Transform groundObject;
private readonly float jumpForce = 15f; // Jumping power size
private readonly float maxHeightDiff = 0.15f; // Allow the maximum height difference between the character and the ground
private readonly float toleranceAngle = 15f; // Maximum allowable tilt angle for the character
private void Awake()
{
playerRigidbody = GetComponent();
}
private void Control()
{
if (common.isTilted(transform, toleranceAngle)) {
return;
}
// 跳跃
if (Input.GetKeyDown(KeyCode.Space)) {
float playerHeight = transform.position.y; // Get character height
float groundHeight = groundObject.position.y; // Get ground height
float heightDiff = Mathf.Abs(playerHeight - groundHeight);
if (heightDiff < maxHeightDiff) {
moveControl.Jump(playerRigidbody, jumpForce);
}
}
// Obtain the camera direction (ignore the Y-axis rotation of the camera, ensure that the character only moves in the XZ plane)
Transform cameraTrans = Camera.main.transform;
// Transform cameraTrans = GameObject.Find("PlayerCamera").transform;
Vector3 cameraForward = new Vector3(cameraTrans.forward.x, 0, cameraTrans.forward.z).normalized;
Vector3 cameraRight = new Vector3(cameraTrans.right.x, 0, cameraTrans.right.z).normalized;
Vector3 moveDirection = Vector3.zero;
// Conventional logic for controlling character movement
if (Input.GetKey(KeyCode.W)) {
moveDirection += cameraForward;
}
if (Input.GetKey(KeyCode.S)) {
moveDirection -= cameraForward;
}
if (Input.GetKey(KeyCode.A)) {
moveDirection -= cameraRight;
}
if (Input.GetKey(KeyCode.D)) {
moveDirection += cameraRight;
}
moveControl.MoveForRigidbody(playerRigidbody, moveDirection.normalized, speed);
}
private void FixedUpdate()
{
Control();
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... g-in-unity
Как избежать чувства неровности при движении в единстве? ⇐ C#
Место общения программистов C#
-
Anonymous
1737901395
Anonymous
Я создал игрока в Unity, добавил к нему компонент твердого тела и реализовал эффект движения, но фактический эффект при движении заставил меня чувствовать себя немного дергающимся и не таким плавным (по сравнению с использованием Transform). Как добиться эффекта плавного движения?
Демонстрационное видео «Трансформирование»
Демонстрационное видео «Rigidbody»
Вот все соответствующие коды для управления движением персонажа:
using UnityEngine;
using UnityEngine.EventSystems;
public class Common
{
// Detect tilt status
public bool isTilted(Transform trans, float toleranceAngle)
{
return Vector3.Angle(trans.up, Vector3.up) > toleranceAngle;
}
}
public class MoveControl
{
public Vector3 GetMoveValue(Vector3 direction, float speed)
{
return speed * direction * Time.deltaTime;
}
public void MoveDirectly(Transform trans, Vector3 direction, float speed)
{
trans.Translate(GetMoveValue(direction, speed));
}
public void Jump(Rigidbody rb, float jumpForce)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
public void MoveForRigidbody(Rigidbody rb, Vector3 direction, float speed)
{
// Using Vector3.Lerp for smooth interpolation and reducing roughness in physical simulations
Vector3 newPosition = rb.position + direction * speed * Time.fixedDeltaTime;
rb.MovePosition(Vector3.Lerp(rb.position, newPosition, speed * Time.fixedDeltaTime));
}
}
public class PlayerControl : MonoBehaviour
{
public float speed = 15f; // Move speed
// Instantiate common script
private Common common = new();
private MoveControl moveControl = new();
private Rigidbody playerRigidbody;
// other logic
// Ground objects used for jump height detection
public Transform groundObject;
private readonly float jumpForce = 15f; // Jumping power size
private readonly float maxHeightDiff = 0.15f; // Allow the maximum height difference between the character and the ground
private readonly float toleranceAngle = 15f; // Maximum allowable tilt angle for the character
private void Awake()
{
playerRigidbody = GetComponent();
}
private void Control()
{
if (common.isTilted(transform, toleranceAngle)) {
return;
}
// 跳跃
if (Input.GetKeyDown(KeyCode.Space)) {
float playerHeight = transform.position.y; // Get character height
float groundHeight = groundObject.position.y; // Get ground height
float heightDiff = Mathf.Abs(playerHeight - groundHeight);
if (heightDiff < maxHeightDiff) {
moveControl.Jump(playerRigidbody, jumpForce);
}
}
// Obtain the camera direction (ignore the Y-axis rotation of the camera, ensure that the character only moves in the XZ plane)
Transform cameraTrans = Camera.main.transform;
// Transform cameraTrans = GameObject.Find("PlayerCamera").transform;
Vector3 cameraForward = new Vector3(cameraTrans.forward.x, 0, cameraTrans.forward.z).normalized;
Vector3 cameraRight = new Vector3(cameraTrans.right.x, 0, cameraTrans.right.z).normalized;
Vector3 moveDirection = Vector3.zero;
// Conventional logic for controlling character movement
if (Input.GetKey(KeyCode.W)) {
moveDirection += cameraForward;
}
if (Input.GetKey(KeyCode.S)) {
moveDirection -= cameraForward;
}
if (Input.GetKey(KeyCode.A)) {
moveDirection -= cameraRight;
}
if (Input.GetKey(KeyCode.D)) {
moveDirection += cameraRight;
}
moveControl.MoveForRigidbody(playerRigidbody, moveDirection.normalized, speed);
}
private void FixedUpdate()
{
Control();
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79388673/how-to-avoid-the-feeling-of-unevenness-when-moving-in-unity[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия