Unity-2D Platformer Controller响应性问题

时间:2018-07-07 20:08:52

标签: unity3d controller

我一直在为2D平台游戏设计一些基本控件,并设法获得了我在移动和跳跃时一直在寻找的感觉,但是有些事情不太正确,反应也不是很好。

大多数输入都被检测到,但是很多时候,例如,完全忽略了按下某个键进行跳跃的简单动作,并且在正确的时间按下了键,玩家最终摔倒了。如果这很重要,我不认为我正在使用低规格的笔记本电脑进行开发。  

看看其他一些问题,一直有人说输入检测应该在Update函数内部,而与物理相关的东西应该在FixedUpdate上,但是,就我而言,一直不清楚哪个函数应该到底是什么。知道它应该像这样...对吗?


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {
    public float speed;
    public float jumpForce;
    public float groundCheckRadius;

    public Transform groundCheck;
    public LayerMask groundMask;

    private float direction;

    private bool facingRight;
    private bool shouldJump;
    private bool isGrounded;
    private bool shouldFall;

    private SpriteRenderer renderer;
    private Rigidbody2D rigidbody;

    void Awake() {
        this.renderer = GetComponent<SpriteRenderer>();
        this.rigidbody = GetComponent<Rigidbody2D>();
    }


    void Start () {
        this.facingRight = true;
        this.shouldJump = false;
        this.isGrounded = false;
        this.shouldFall = false;
    }


    void Update () {
        this.direction = Input.GetAxisRaw("Horizontal");
        this.isGrounded = Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask);
        this.shouldJump = Input.GetKeyDown(KeyCode.S) && this.isGrounded;

        if (this.facingRight && this.direction < 0 || !this.facingRight && this.direction > 0)
            this.Flip();

        if (Input.GetKeyUp(KeyCode.S) && this.rigidbody.velocity.y > 0)
            this.shouldFall = true;
    }

    void FixedUpdate() {
        Vector2 velocity = this.rigidbody.velocity;

        if (this.shouldFall) {
            velocity.y = 0f;
            this.shouldFall = false;
        }

        if (this.shouldJump)
            velocity.y = this.jumpForce;

        velocity.x = this.speed * this.direction;

        this.rigidbody.velocity = velocity;
    }

    private void Flip() {
        this.renderer.flipX = this.facingRight;
        this.facingRight = !this.facingRight;
    }
}



我不确定由于缺少响应性跳转而导致我是否正确理解了Update vs FixedUpdate的想法,我猜测如果我再添加一些机制,以后它们的反应会相同或更差。

0 个答案:

没有答案