14 de jan. de 2020

Jumping like Mario


We can control:
  • The Highest Jump Height (JumpVelocity and Gravity Scale)
  • The velocity he goes Up (JumpVelocity and Gravity Scale)
  • The velocity he goes Down (Fall Multiplier)
  • The Lowest Jump Height (Low Jump Multiplier)






 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Jump : MonoBehaviour
{
    Rigidbody2D rb;

    public float jumpVelocity;
    public float speed = 5;

    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    float hor;

    public LayerMask whatIsGround;
    public Transform feetPos;
    public float checkRadius;
    bool isGrounded;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    private void Update()
    {
        hor = Input.GetAxis("Horizontal");

        isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            GetComponent<Rigidbody2D>().velocity = Vector2.up * jumpVelocity;
        }
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(hor * speed, rb.velocity.y);

        if (rb.velocity.y < 0) // if is falling, accelerate
        {
            rb.velocity += Vector2.up * (-fallMultiplier);
        }
        else if (rb.velocity.y > 0 && !Input.GetButton("Jump")) // if is going up and not pressing button, force down
        {
            rb.velocity += Vector2.up * (-lowJumpMultiplier);
        }
    }
}

Nenhum comentário: