繁体   English   中英

跳跃时更改角色方向

[英]Change Character Direction While Jumping

我正在制作2D平台游戏,并且按照教程构建角色。 该角色工作正常,但在跳跃时不允许改变空中方向。 我该如何添加才能使我的角色能够在跳跃中改变方向?

基本运动所使用的代码如下:

void Update()
{

    CharacterController controller = GetComponent<CharacterController>();
    float rotation = Input.GetAxis("Horizontal");
    if(controller.isGrounded)
    {
        moveDirection.Set(rotation, 0, 0);
        moveDirection = transform.TransformDirection(moveDirection);

        //running code
        if(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) //check if shift is held
        { running = true; }
        else
        { running = false; }

        moveDirection *= running ? runningSpeed : walkingSpeed; //set speed

        //jump code
        if(Input.GetButtonDown("Jump"))
        {
            jump();
        }
    }

    moveDirection.y -= gravity * Time.deltaTime;

    controller.Move(moveDirection * Time.deltaTime);


}

编辑:忘记包括jump()的代码,那可能很重要...

 void jump()
{
    moveDirection.y=jumpHeight;
    transform.parent=null;
}

仅当字符接地时,才更新moveDirection向量:

if(controller.isGrounded)

当玩家跳跃时, isGrounded设置为false,因此moveDirection将不会更新(重力除外)。

我想您不想在跳跃时影响角色的速度(除非它应该在空中飞行或行走)。 我猜您想在其跳跃时更改其方向,因此您可以直接修改变换,使其随输入旋转。

就像是:

else
{
   float amountOfRotation = Input.GetAxis("...") * rotationScaleFactor; 
   transform.RotateAround(transform.position, transform.up, Time.deltaTime * amountOfRotation);
}

编辑

我从未使用过它,但我认为CharacterController仅在对象接地时才可移动。 因此,如果要在播放过程中移动它,请不要使用Move方法,而应直接编辑GameObject的变换:

else
{
   float additionalForwardSpeed = Input.GetAxis("...") * speedScaleFactor;  
   transform.Translate(transform.forward * Time.deltaTime * additionalForwardSpeed ); //translate
}

上面的代码应提高对象在本地正向方向上的速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM