2D人物移动代码

private GameObject rigid;
private Vector2 input;
private Vector2 mousePos; //鼠标的位置
public float Speed;//人物的移动速度一般设为 public 可以随时调节
Private Animator Ani; //获取动画让人物的移动逼真

void Start()
{
//在开始的时候获取这些组件
animantor = GetComponent<Animator>();
rigidbody = GetComponent<Rigidbody2D>();
}

void Update()
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");

rigid.velocity = input.normalized*speed;//normalized 单位向量,防止因为同时键入w d使得向
//量相加
mousePso = Camera.main.ScreenToWorldPoint(Input.mousePosition);
  if (mousePso.x > transform.position.x)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
        }
        else 
        {
            transform.rotation = Quaternion.Euler(new Vector3(0, 180, 0));
        }
}
If(input !=Vector2.zero )
{
Ani.SetBool("Ismoving", true);//ismoving 移动控制参数
}
Else
{
Ani.SetBool("Ismoving", false);
}

上述代码适用于2D开放地图,在该地图中人物不可以跳跃只能上下左右走动。

Public float movespeed;
Private float jumpspeed;
 [Range(0, .3f)]
 [SerializeField] private float checkRadius = .2f;
 private Rigidbody2D rigidbody;
 private Animator animator;
//声明是否能进行 二段跳
 private bool DoubleJump=true;
//获取输入信息
private float inputX;
[SerializeField] private bool isGround = true;
[SerializeField] private LayerMask layer;
Void start()
{
    rigidbody = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}

Void update()
{
//返回值是-1,1 是瞬间变换没有变换过程
inputX = Input.GetAxisRaw(“Horizontal”);
//画个圆 参数(圆的圆心,圆的半径,与那个层级接触)
isGround = Physics2D.OverlapCircle(transform.position, checkRadius, layer);
Move();
Jump(); 
Flip();

}
Private void Flip()
{
If(inputX==-1)
{
Transform.localScale = new Vector3(-1,1,1);
}
else if(inputX==1)
{
Transform.localScale = new Vector3(1,1,1);
}
}
Private void Jump(){ 
If(! isGround && Input.GetButtonDown("Jump")) 
{
 DoubleJump = true;
 rigidbody.velocity = new Vector2(0, jumpSpeed );
animator.SetTrigger("Jump");
}
If(isGround && Input.GetButtonDown("Jump")&&DoubleJump ) //二段跳 一般可以设置第二 //次跳跃的高度稍微比第一次低一点
{
rigidbody.velocity = new Vector2(0, jumpSpeed );
animator.SetTrigger("Jump");
DoubleJump = false;
}
}

Privete void Move()
{
 rigidbody.velocity = new Vector2(inputX * moveSpeed, rigidbody.velocity.y);
animator.SetBool("isGround", isGround);
animator.SetFloat("Horizontal", rigidbody.velocity.x);
 animator.SetFloat("Vertical", rigidbody.velocity.y);
}

适用于可以跳跃的2D游戏

上一篇:Unity学习记录:价值两万的课程笔记,看到就是赚到,快收藏起来吧


下一篇:Canvas加动画,实现火柴人跳绳效果,附Android面经