如何制作2D平台小游戏 2

一、创建角色
1.创建角色和挂载脚本

在这里插入图片描述

在这里插入图片描述

2. 实现简单移动
两种移动方法:
Rigidbody2D rb;

public float playerSpeed = 5f; //移动速度
void Start()
{
   rb=GetComponent<Rigidbody2D>();  //获取2D组件
}
void Update() //关于输入输出  每帧调用
{
   1 没有惯性,立马停下
   moveX = Input.GetAxisRaw("Horizontal");//获取x轴位置  a -1 , 0 , d 1
   2 有惯性,会向前移动一点点
   moveX = Input.GetAxis("Horizontal");//获取x轴位置  a -1 , 0 , d 1
   rb.velocity = new Vector2(moveX * playerSpeed, rb.velocity.y);
}
3. 实现左右移动翻转

① 没惯性

rb.velocity = new Vector2(moveX * PlayerSpeed, rb.velocity.y);
if (moveX != 0)
{
  transform.localScale = new Vector3(moveX, 1, 1);  
  //用moveX控制transform组件中的Sclae从而改变角色方向
}

② 有惯性

if (facingRight==false && moveX > 0)
{
	Flip();
}
else if (facingRight==true && moveX<0)
{
	Flip();
}

}
private void Flip()//翻转
{
	facingRight=!facingRight;
	Vector3 playerScale = transform.localScale;
	playerScale.x *= -1; //实现翻转
	transform.localScale=playerScale;
}
4. 实现跳跃
1) 简单跳跃
[Range(1, 10)]
public float jumSpeed = 5f;//跳跃速度
private bool moveJump; //跳跃输入

void Updata
{
	 moveJump = Input.GetButtonDown("Jump"); //获取空格跳跃键

     if(moveJump)
     {
        rb.velocity = Vector2.up*jumSpeed;  //up代表向上
     }
}
注:缺点很多 可以一直跳跃
2) 优化跳跃

在这里插入图片描述

1)让角色着地后才能跳跃
要给平台设置为图层,给角色添加一个检测点来,判断是否在地面上
public bool isGrounded; //判断是否在地面上

public Transform groundCheck;//检测点

public LayerMask ground;//设置图层,用来判断,是否在地面上

private void FixedUpdate()
{
   isGrounded = Physics2D.OverlapCircle(groundCheck.position,0.1f, ground); 
   //如果在地面就为True;
   Move();
}
2)设置重力加成
角色下落时给一个更大的重力加速度,区分跳跃和下落的速度
public float fallAddition = 3.5f;//下落重力加成

public float jumpAddtion = 1.5f;//跳跃重力加成
private void Jump()
{
    if (rb.velocity.y < 0) 
    {                    
        rb.velocity+=Vector2.up*Physics2D.gravity.y(fallAddition1)*   
        Time.fixedDeltaTime;
        //当下落时给一个更大的重力加成
    }
    else if(rb.velocity.y > 0&&!jumpHold) 
    {
         rb.velocity += Vector2.up * Physics2D.gravity.y * (jumpAddtion -                      1)*Time.fixedDeltaTime;
        //当长按跳跃后下落速度和直接下落产生区别,优化手感
     }
}
3)给图层设置以下操作

1)给平台设置
在这里插入图片描述

在这里插入图片描述

4)二跳和多段跳
public int jumpCount = 2; //跳跃次数
private bool isJump;  //传递作用,表示跳跃状态

if (moveJump&&jumpCount>0)
{
     isJump = true;
}

if(isGrounded)
{
   jumpCount = 2;  //当检测到在地面时,则可以二段跳
}
if (isJump)
{
     rb.AddForce(Vector2.up * jumSpeed,ForceMode2D.Impulse);  //up代表向上  
     //Impulse瞬间加上去的力
   
     jumpCount--;
     isJump = false;
}
//用isJump来判断是否能二段跳,当跳跃次数为0时isJump为false,则不能二段跳
  

后续我们为角色添加粒子他特效和跑步,跳跃动画

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值