Bomb Guy Script (一):PlayerController

本文介绍了一个简单的2D游戏中的玩家角色控制脚本,通过Unity引擎实现。该脚本包括了角色的移动、跳跃功能,并加入了地面检测逻辑来判断角色是否处于地面上,从而决定是否能够跳跃。

Player控制脚本

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

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    

    public float speed;
    public float jumpForce;

    [Header("Ground Check")]
    public Transform checkTrans;
    public LayerMask checkLayer;//存储可以跳跃的layer
    public float radius;

    [Header("States Check")]
    public bool isGround;
    public bool canJump = false;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        InputCheck();
    }

    void FixedUpdate()//每0.02秒调用,时间固定
    {
        Movement();
        Jump();
        PhysicsCheck();
    }

    private void Movement()//人物移动方法
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);
        //翻转人物
        if (horizontalInput != 0){
            //int dir = horizontalInput > 0 ? 1 : -1;
            //transform.localScale = new Vector3(dir, 1, 1);//使用scale实现翻转
            int dir = horizontalInput > 0 ? 0 : -1;
            transform.rotation = Quaternion.Euler(0, dir * 180, 0);
        }
    }

    private void InputCheck()//输入检测
    {
        if (Input.GetKeyDown(KeyCode.W)&&isGround){
            canJump = true;
        }
    }

    private void Jump()
    {
        if (canJump){
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            //rb.gravityScale = 4;//跳跃后修改重力大小
            canJump = false;
        }
    }

    private void PhysicsCheck()
    {
        isGround = Physics2D.OverlapCircle(checkTrans.position, radius, checkLayer);
        if (isGround)//回到地面后改回重力的大小
            rb.gravityScale = 1;
        else
            rb.gravityScale = 4;
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(checkTrans.position, radius);
    }

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值