charactor controller角色平衡木问题解决办法

本文介绍了一种在Unity中使用CharacterController实现角色在平衡木上行走的方法。通过自定义速度、重力等参数,并手动应用重力效果,使得角色能够稳定地在细长的平衡木上移动并跳跃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  charactor controller角色做平衡木的问题,和小球走平衡木不一样,charctor controller是不可以对地面产生压力的,无论角色是否加了刚体,charactor controller都只具有自由下落,而不具有对地面压力。如果换成box collider等碰撞检测,上下楼梯角色运动的时候很容易倒下。针对这个问题,做出了以下解决方案:

var speed = 10.0;

var gravity = 10.0;

var maxVelocityChange = 10.0;

var canJump = true;

var jumpHeight = 2.0;

private var grounded = false;

@script RequireComponent(Rigidbody, CapsuleCollider)

function Awake ()

{

    rigidbody.freezeRotation = true;

    rigidbody.useGravity = false;

}

function FixedUpdate ()

{

    if (grounded)

        // Calculate how fast we should be moving

        var targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

        targetVelocity = transform.TransformDirection(targetVelocity);

        targetVelocity *= speed;

        // Apply a force that attempts to reach our target velocity

        var velocity = rigidbody.velocity;

        var velocityChange = (targetVelocity - velocity);

        velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);

        velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);

        velocityChange.y = 0;

        rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);

        // Jump

        if (canJump && Input.GetButton("Jump"))

        {

            rigidbody.velocity = Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);

        }

    }

    // We apply gravity manually for more tuning control

    rigidbody.AddForce(Vector3 (0, -gravity * rigidbody.mass, 0));

    grounded = false;

}

function OnCollisionStay ()

{

    grounded = true;   

}

function CalculateJumpVerticalSpeed ()

{

    // From the jump height and gravity we deduce the upwards speed

    // for the character to reach at the apex.

    return Mathf.Sqrt(2 * jumpHeight * gravity);

}

转载于:https://www.cnblogs.com/sudiwangluo/p/5969695.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值