2D吃豆人一些自以为有用的功能总结

本文介绍如何在Unity中实现2D游戏角色的移动、跳跃及转向功能,包括使用Rigidbody2D进行物理交互,Animator管理动画状态,以及通过TileMap快速构建游戏场景的方法。同时,分享了摄像机跟随玩家的实现技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现2D主角移动,跳跃和转头函数

public bool facingRight=true;
public float movespeed;
public float moveForce = 365f;
public float maxSpeed = 5f;
public float jumpForce = 1000f;

private Transform groundCheck;
private bool grounded = false;
private Animator anim;
 public bool jump = false;
void Flip()
{
  facingRight=!facingRight;
  Vector3 theScale=transform.localScale;
  theScale.x*=-1;
  transform.localScale=theScale;
}
void Start () {
        anim = GetComponent<Animator>();
 }
void Update () {
        if (Input.GetButtonDown("Jump"))
            jump = true;
            GetComponent<Rigidbody2D>().
            constraints = RigidbodyConstraints2D.FreezeRotation;
 }
 void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        anim.SetFloat("Speed", Mathf.Abs(h));
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        if (h * rb.velocity.x < maxSpeed)
            rb.AddForce(Vector2.right * h * moveForce);
        if (Mathf.Abs(rb.velocity.x) > maxSpeed)
            rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * maxSpeed, rb.velocity.y);
        if (h > 0 && !facingRight) Flip();
        else if (h < 0 && facingRight) Flip();
        if(jump)
        {
            anim.SetTrigger("Jump");
            rb.AddForce(new Vector2(0, jumpForce));
            jump = false;
        }
    }
}

使用TileMap快速搭建2D游戏场景

首先在场景创建TileMap在这里插入图片描述
接着打开Talpaletter
在这里插入图片描述
然后把要绘制的场景,整个拖进。点击画笔就可以在scene绘制

给场景赋予碰撞体的话需要在给Grid的Tilemap添加Tilemap collider2D和rigidbody 2D组件,然后为了让地面不受重力掉下去或者被它上表面的物体压下去,将rigidbody 2D设为静态(static)刚体
//此功能是转载别人的,侵删
在这里插入图片描述

Rigidbody2D锁定对象旋转,使其装上碰撞器时不会随意翻转角度

GetComponent().constraints = RigidbodyConstraints2D.FreezeRotation;

实现摄像机跟随player

把以下代码挂在主相机

public GameObject player;
public float speed;

public float minPos;
public float maxPos;
void Start()
{
}
void Update()
{
  FixCameraPos();
}
void FixCameraPos()
{
  float pPoX=player.transform.position.x;
  float cPoX=transform.position.x;
if(pPoX-cPoX>3)
{
  transform.positon=new Vector3(cPoX+speed*Time.deltaTime,transform.position.y,transform.position.z);
  
}if(pPoX-cPoX<-3)
{
  transform.position=new Vector3(cPoX-speed*Time.deltaTime,transform.position.y,transform.position.z);
}
float realPosX=Mathf.Clamp(transform.position.x,minPosx,maxPox);//限制摄像机移动

transform.position=new Vector3(realPosX,transform.position.y,transform.position.z);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值