目录
我使用的Unity版本为2020.3.13f1c1,代码编辑器VSCode
导入素材
素材均来自https://itch.io/的免费素材
我选择的是https://rvros.itch.io/animated-pixel-hero素材
导入到Unity后全选人物图片,在右侧的检测器里更改一些参数,然后点击应用
修改像素大小为16
过滤模式选择-点(无过滤器),这样可以使图片不会模糊
人物移动
将adventurer-idle-00(待机图片)拖入到场景内,修改名字为Player
为Player添加2D刚体和2D碰撞盒
·
修改碰撞盒贴合Player即可
在项目窗口新建一个物理材质,命名为Player,将Friction和Bounciness都设置为0,并将该材质拖入到刚体的物理材质内 ,这样做的原因是不会让人物卡在墙上
代码编写,新建文件夹Scripts,并在其目录新建脚本,命名为 PlayerControl.cs
双击打开PlayerControl.cs,开始编写移动代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
#region 组件
private Rigidbody2D rb;//2D刚体
#endregion
#region 公开参数
[Header("移动参数")]
public float moveSpeed;//人物移动速度
#endregion
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Move();
}
// 人物移动 和 转向
private void Move()
{
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * moveSpeed, rb.velocity.y);
//判断人物的朝向
if (moveX > 0)
transform.localScale = new Vector3(1, 1, 1);
else if (moveX < 0)
transform.localScale = new Vector3(-1, 1, 1);
}
}
返回Unity,测试
测试之前先在场景内放一个物体,并添加碰撞盒,这样让角色站在上面
人物跳跃
跳跃代码,在移动代码上添加
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
#region 组件
private Rigidbody2D rb;
#endregion
#region 公开参数
[Header("移动参数")]
public float moveSpeed;//人物移动速度
[Header("跳跃参数")]
public float jumpForce;//跳跃的力 (及高度)
public float jumpAddForce;//长按跳跃 增加的高度
public float jumpTime;//按下跳跃键的时间
public float jumpStartTime;//初始时间
public bool isJump;//是否正在跳跃
[Header("环境检测")]
public float checkRadius;//检测地面偏移
public LayerMask whatIsGround;//地面图层
public Transform feetPos; //地面检测点
#endregion
#region 私有参数
public bool isGround;//是否在地面
#endregion
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
isGround = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
Jump();
}
private void FixedUpdate()
{
Move();
}
// 人物移动 和 转向
private void Move()
{
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * moveSpeed, rb.velocity.y);
//判断人物的朝向
if (moveX > 0)
transform.localScale = new Vector3(1, 1, 1);
else if (moveX < 0)
transform.localScale = new Vector3(-1, 1, 1);
}
//人物的跳跃
private void Jump()
{
//按下跳跃键
if (Input.GetKeyDown(KeyCode.Space) && isGround)
{
//将跳跃锁定
isJump = true;
//跳跃
rb.velocity = Vector2.up * jumpForce;
jumpTime = jumpStartTime;
}
//长按跳跃键
if (Input.GetKey(KeyCode.Space) && isJump == true)
{
//当长按时间大于零
if (jumpTime > 0)
{
//在长按跳跃这段时间,跳跃
rb.velocity = Vector2.up * jumpForce;
//长按时间减去每一帧
jumpTime -= Time.deltaTime;
}
}
else
{
isJump = false;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJump = false;
}
}
}
哦,对了,刚体记得冻结Z轴,不然人物会倒的
至此人物移动和跳跃就写完了