玩家行走、转身、动画转换:
玩家跳跃:![](https://img-blog.csdnimg.cn/2d0eabddab694294aca4d1678d8c097d.png)
代码部分Player_move:
using UnityEngine;
public class Player_move : MonoBehaviour
{
Animator ani;
bool faceRight = true;//翻面
Rigidbody2D rig;
public bool ground=false;//是否接触地面
public Transform m_Check;
void Start()
{
ani = GetComponent<Animator>();
rig = GetComponent<Rigidbody2D>();
}
void Update()
{
//移动
float h = Input.GetAxis("Horizontal");
ani.SetFloat("speed", Mathf.Abs(h));//对h取正,并没有改变h原本的值
if ((faceRight && h < 0)||(!faceRight && h > 0))
{
Flip();
}
rig.AddForce(Vector2.right * h * 10);
//限速
if (rig.velocity.x > 4)
{
rig.velocity = new Vector2(5, rig.velocity.y);
}
if (rig.velocity.x < -4)
{
rig.velocity = new Vector2(-5, rig.velocity.y);
}
//跳跃
//第一种方法:碰撞体OnCollisionEnter2D()
//第二种方法:线碰撞自动检测ground:当前位置到目标位置画出一条线,与包围盒发生碰撞,可返回bool值
//辅助线Debug.DrawLine(transform.position, m_Check.position,Color.red,0.1f);
ground = Physics2D.Linecast(transform.position, m_Check.position,
1<<LayerMask.NameToLayer("Ground"));
if (ground && Input.GetButtonDown("Jump"))
{
rig.AddForce(Vector2.up * 300);
//ground = false;//(方法一用到)离开地面
}
}
void Flip()
{
Vector3 v = transform.localScale;
v.x *= -1;
transform.localScale = v;
faceRight = !faceRight;
}
//(方法一用到)
//private void OnCollisionEnter2D(Collision2D collision)
//{
// ground = true;
//}
}