Unity2D游戏使游戏角色移动的脚本

想要使游戏角色移动起来

  1. 首先需要给游戏角色添加(Rigidbody)刚体、(Collider 2D)碰撞体、(Script)脚本。
    在这里插入图片描述
  2. 能使游戏角色移动起来的脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    //获得角色刚体
    private Rigidbody2D rb;
    //获得角色碰撞器,游戏需要所以特别使用方形的collider
    private BoxCollider2D coll;

    [Header("移动参数")]
    //设定角色的移动速度
    public float speed = 8f;

	//判断x轴力的方向
    public float xVelocity;

	void Start()
    {
        //GetComponent< >():获取对象中指定类型的控件(脚本)
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<BoxCollider2D>();
	}

	private void FixedUpdate()
    {
        //写好的函数需要在FixedUpdate()中进行调用
        GroundMovement();
    }

	void GroundMovement() 
    {
        //获得在键盘上输入的移动
        xVelocity = Input.GetAxis("Horizontal");//-1f  1f 0
        //使角色移动
        rb.velocity = new Vector2(xVelocity * speed, rb.velocity.y);
        //调用判断角色面向左右的函数
        FilpDirction();
    }

	//判断游戏角色面向左右的函数
	void FilpDirction()
    {
        //如果x轴的速度小于0,游戏角色就会面向左
        if (xVelocity < 0)
            transform.localScale = new Vector3(-1, 1, 1);
        //如果x轴的速度大于0,游戏角色就会面向右
        if (xVelocity > 0)
            transform.localScale = new Vector3(1, 1, 1);
    }

完成以上操作就可以使游戏角色进行左右移动。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_细嗅蔷薇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值