Unity 3D C#Player移动跳跃错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity 3D C#Player移动跳跃错误相关的知识,希望对你有一定的参考价值。
所以我一直在制作一个脚本,让球在x-asis上以恒定速度移动,但也可以控制。当我按空格键跳转。除非按下按钮5到6次,否则它不会跳转。如果你第一次跳球,如果你反复敲击空格键它会跳,但是如果你不管它并让它滚动然后再尝试跳。它不会让你。我很困惑。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Speed : MonoBehaviour
{
public float sspeed = 7.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector2 moveDirection = Vector2.zero;
void Start()
{
}
void Update()
{
if (GetComponent<CharacterController>().isGrounded)
{
moveDirection = new Vector2();
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= sspeed;
moveDirection.x = sspeed;
}
else if (GetComponent<CharacterController>())
{
moveDirection.x = gravity;
}
moveDirection.x -= gravity * Time.deltaTime;
GetComponent<CharacterController>().Move(moveDirection * Time.deltaTime);
CharacterController player = GetComponent<CharacterController>();
if (GetComponent<CharacterController>().isGrounded)
{
moveDirection = new Vector2();
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= sspeed;
if (Input.GetKeyDown("space"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
GetComponent<CharacterController>().Move(moveDirection * Time.deltaTime);
}
}
答案
有一个更好的方法:
Rigidbody body = GetComponent<Rigidbody>();
if(Input.GetKeyDown(KeyCode.Space)){
body.AddForce(transform.up*jumpSpeed);
}
另一答案
试试这个吧
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConstantMoveByX : MonoBehaviour
{
[SerializeField]
private float constantSpeed = 10.0f;
[SerializeField]
private float jumpForce = 25.0f;
[SerializeField]
private float gravity = 9.8f;
private CharacterController characterController;
private Vector3 moveDirection = Vector3.zero;
private void Start()
{
characterController = GetComponent<CharacterController>();
}
private void Update()
{
if (characterController.isGrounded)
{
moveDirection = Vector3.right * constantSpeed;
moveDirection = transform.TransformDirection(moveDirection);
moveDirection = moveDirection * constantSpeed;
if (Input.GetKeyDown(KeyCode.Space))
{
moveDirection.y = jumpForce;
}
}
moveDirection.y = moveDirection.y - (gravity * Time.deltaTime);
characterController.Move(moveDirection * Time.deltaTime);
}
}
以上是关于Unity 3D C#Player移动跳跃错误的主要内容,如果未能解决你的问题,请参考以下文章
Unity3D c# 2D Game Camera Follow 正在跳跃