Я работаю над проектом Unity 3D и столкнулся с проблемой прыжков игрока. Игрок может прыгнуть только один раз, и после первого прыжка он не может прыгнуть снова, даже после того, как снова приземлится на землю. Кроме того, условие isGrounded всегда возвращает true, даже если игрок не находится на земле.
Я использую CharacterController и Physics.CheckSphere для обнаружения земли. Ниже приведен код, который я использую:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10f; // Movement speed
public float jumpForce = 10f; // Jump force
private bool canJump = true; // Flag to check if the player can jump
private CharacterController controller;
private Vector3 velocity; // Used to apply gravity and jump force
public Transform groundCheck; // Position for ground detection
public float groundDistance = 0.3f; // Radius of ground check sphere (adjustable)
public LayerMask groundMask; // Layer mask for ground detection
void Start()
{
controller = GetComponent();
}
void Update()
{
// Ground check using Physics.CheckSphere
bool isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
// Debugging: Output whether the player is grounded and the position of groundCheck
Debug.Log("Is Grounded: " + isGrounded + " | GroundCheck Position: " + groundCheck.position);
// When grounded, reset downward velocity and allow jumping
if (isGrounded)
{
if (velocity.y < 0)
{
velocity.y = -2f; // Small downward force to keep player grounded
}
canJump = true; // Allow jumping when grounded
}
else
{
canJump = false; // Disable jumping when not grounded
}
// Player movement
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 move = transform.right * moveX + transform.forward * moveZ;
controller.Move(move * speed * Time.deltaTime);
// Jumping logic (only allow jump when grounded)
if (Input.GetButtonDown("Jump") && canJump)
{
// Apply jump force
velocity.y = Mathf.Sqrt(jumpForce * -2f * Physics.gravity.y);
// Disable jumping until grounded again
canJump = false;
}
// Apply gravity to simulate falling
velocity.y += Physics.gravity.y * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
void OnCollisionEnter(Collision collision)
{
// If the player collides with the ground, set canJump to true
if (collision.gameObject.CompareTag("Ground"))
{
canJump = true; // Allow jumping again when touching the ground
}
}
// Visualize the ground check area
void OnDrawGizmos()
{
if (groundCheck != null)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(groundCheck.position, groundDistance); // Visualize the ground check area
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -even-when
Unity: логика прыжков игрока не работает должным образом — isGrounded всегда верен, даже когда он не находится на земле ⇐ C#
Место общения программистов C#
1735398896
Anonymous
Я работаю над проектом Unity 3D и столкнулся с проблемой прыжков игрока. Игрок может прыгнуть только один раз, и после первого прыжка он не может прыгнуть снова, даже после того, как снова приземлится на землю. Кроме того, условие isGrounded всегда возвращает true, даже если игрок не находится на земле.
Я использую CharacterController и Physics.CheckSphere для обнаружения земли. Ниже приведен код, который я использую:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10f; // Movement speed
public float jumpForce = 10f; // Jump force
private bool canJump = true; // Flag to check if the player can jump
private CharacterController controller;
private Vector3 velocity; // Used to apply gravity and jump force
public Transform groundCheck; // Position for ground detection
public float groundDistance = 0.3f; // Radius of ground check sphere (adjustable)
public LayerMask groundMask; // Layer mask for ground detection
void Start()
{
controller = GetComponent();
}
void Update()
{
// Ground check using Physics.CheckSphere
bool isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
// Debugging: Output whether the player is grounded and the position of groundCheck
Debug.Log("Is Grounded: " + isGrounded + " | GroundCheck Position: " + groundCheck.position);
// When grounded, reset downward velocity and allow jumping
if (isGrounded)
{
if (velocity.y < 0)
{
velocity.y = -2f; // Small downward force to keep player grounded
}
canJump = true; // Allow jumping when grounded
}
else
{
canJump = false; // Disable jumping when not grounded
}
// Player movement
float moveX = Input.GetAxis("Horizontal");
float moveZ = Input.GetAxis("Vertical");
Vector3 move = transform.right * moveX + transform.forward * moveZ;
controller.Move(move * speed * Time.deltaTime);
// Jumping logic (only allow jump when grounded)
if (Input.GetButtonDown("Jump") && canJump)
{
// Apply jump force
velocity.y = Mathf.Sqrt(jumpForce * -2f * Physics.gravity.y);
// Disable jumping until grounded again
canJump = false;
}
// Apply gravity to simulate falling
velocity.y += Physics.gravity.y * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
void OnCollisionEnter(Collision collision)
{
// If the player collides with the ground, set canJump to true
if (collision.gameObject.CompareTag("Ground"))
{
canJump = true; // Allow jumping again when touching the ground
}
}
// Visualize the ground check area
void OnDrawGizmos()
{
if (groundCheck != null)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(groundCheck.position, groundDistance); // Visualize the ground check area
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79306001/unity-player-jump-logic-not-working-properly-isgrounded-always-true-even-when[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия