> 文档中心 > Unity2D游戏使游戏角色移动的脚本

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

想要使游戏角色移动起来

  1. 首先需要给游戏角色添加(Rigidbody)刚体、(Collider 2D)碰撞体、(Script)脚本。
    Unity2D游戏使游戏角色移动的脚本
  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);    }

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