Game create Day 20

coding program

today coding is jump action & collision detection|










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

public class PlayerCtrl : MonoBehaviour
{
    public float speed = 5;
    public float jumpForce = 400f;
    private Rigidbody2D rb2d;
    private Animator anim;
    private SpriteRenderer spRenderer;

    private bool isGround;

    // Start is called before the first frame update
    void Start()
    {
        this.rb2d = GetComponent<Rigidbody2D>();
        this.anim = GetComponent<Animator>();
        this.spRenderer = GetComponent<SpriteRenderer>;
    }

    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxisRaw("Horizontal");

        //change sprite direction
        if( x < 0 ){
            spRenderer.flipX = true;
        }else if( x > 0 ){
            spRenderer.flipX = false;
        }

        rb2d.AddForce( Vector2.right * x * speed );

        anim.SetFloat("Speed", Mathf.Abs( rb2d.velocity.x ));

        if( Input.GetButtonDown("Jump") & isGround ){
        
            anim.SelBool("isJump",true);
            rb2d.AddForce( Vector2.up * jumpForce );
        
        }

        float velX = rb2d.velocity.x;
        float velY = rb2d.velocity.y;

        if( velX > 5.0f ){
            rb2d.velocity = new Vector2( 5.0f , velY);
        }
        if( velX < -5.0f ){
            rb2d.velocity = new Vector2( -5.0f , velY);
        }
    }

    private void FixedUpdate()
    {
        isGround = false;


          Vector2 groundPos =
              new Vector2 (
                  transform.position.x;
                  transform.position.y;
              );

          Vector2 groundArea = new Vector2( 0.5f , 0.5f );

          Debug.DrowLine( groundPos + groundArea , groundPos - groundArea , color.red );

          isGround =
              Physics2D.OverlapArea(
                  groundPos + groundArea ,
                  groundPos _ groundArea ,
                  groundLayer
              );

          Debug.log(isGround);
      }

}

コメント

このブログの人気の投稿