在Unity3D中,我的角色总是穿过障碍物

本文关键字:障碍物 角色 Unity3D 我的 | 更新日期: 2023-09-27 18:11:28

在Unity中,我用这个脚本制作了一个测试精灵,但是当我快速跳跃或随机跳跃时,我的角色会从地上掉下来,但当他移动缓慢时,他会保持在地上,但当快速跳跃/降落时,他会掉下来。

using UnityEngine;
using System.Collections;
public class code : MonoBehaviour { 
//void FixedUpdate() {
        /*if (Input.GetKey (KeyCode.LeftArrow)) 
         {
            int Left = 1;
        }
        if (Input.GetKey (KeyCode.RightArrow)) 
        {
            int Right = 1;
        }

        if (Input.GetKey(KeyCode.UpArrow))
        {
        }
        */
public float speed1 = 6.0F;
public float jumpSpeed = 8.0F; 
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void FixedUpdate() {
    CharacterController controller = GetComponent<CharacterController>();
    // is the controller on the ground?
    if (controller.isGrounded) {
        //Feed moveDirection with input.
        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0,        Input.GetAxis("Vertical"));
        moveDirection = transform.TransformDirection(moveDirection);
        //Multiply it by speed.
        moveDirection *= speed1;
        //Jumping
        if (Input.GetButton("Jump"))
            moveDirection.y = jumpSpeed;
        if (Input.GetKey (KeyCode.UpArrow)) 
            moveDirection.y = jumpSpeed;
    }
    //Applying gravity to the controller
    moveDirection.y -= gravity * Time.deltaTime;
    //Making the character move
    controller.Move(moveDirection * Time.deltaTime);
}   
}

在Unity3D中,我的角色总是穿过障碍物

这是每个物理引擎的共同问题。

物理计算是一个昂贵的操作,因此不能每帧都运行。为了减少过热(以降低准确性为代价),Unity每0.02秒才更新一次物理(这个数字是可配置的)。

你可以减少这个数字,但它越小,物理引擎就越过热,它仍然不能保证100%的准确性。要达到100%的准确性,你不应该依赖物理引擎,而是自己做。

下面是检查直线飞行的子弹碰撞的代码(取自我的一个宠物项目)。

IEnumerator Translate()
{
    var projectile = Projectile.transform; // Cache the transform
    while (IsMoving)
    {
        // Calculate the next position the transform should be in the next frame.
        var delta = projectile.forward * ProjectileSpeed * Time.deltaTime;
        var nextPosition = projectile.position + delta;
        // Do a raycast from current position to the calculated position to determine if a hit occurs
        RaycastHit hitInfo;
        if (Physics.Linecast(projectile.position, nextPosition, out hitInfo, CollisionLayerMask))
        {
            projectile.position = hitInfo.point;
            OnCollision(hitInfo); // Ok, we hit
        }
        else projectile.position = nextPosition; // Nope, haven't hit yet
        yield return null;
    }
}

在你的例子中,你只需要在你的角色开始跳跃时做光线投射来确定他是否落地,如果他落地了,你就做一些事情来防止他掉下去。