using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enimy_frog : MonoBehaviour
{
private Rigidbody2D rb;
private Animator anim;
public Collider2D coll;
public Transform leftside,rightside;
public float Speed,JumpForce;
private bool Faceleft = true;
public LayerMask Ground;
private float leftx,rightx;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
coll = GetComponent<Collider2D>();
transform.DetachChildren();
//切断青蛙的父子层关系,防止左右边界跟青蛙一起跑
//当然也可以直接开局获取left/rightside的位置值
leftx = leftside.position.x;
rightx = rightside.position.x;
Destroy(leftside.gameObject);
Destroy(rightside.gameObject);
}
// Update is called once per frame
void Update()
{
SwitchAnim();
}
void Movement()
{
if (Faceleft)
{
if (coll.IsTouchingLayers(Ground))
{
anim.SetBool("jumping",true);
rb.velocity = new Vector2(-Speed, JumpForce);
}
//if (transform.position.x < leftside.position.x)
if (transform.position.x < leftx)
{
rb.velocity = new Vector2(0,0);
transform.localScale = new Vector3(-1,1,1);
Faceleft = false;
}
}
else
{
if (coll.IsTouchingLayers(Ground))
{
anim.SetBool("jumping",true);
rb.velocity = new Vector2(Speed, JumpForce);
}
//if (transform.position.x > rightside.position.x)
if (transform.position.x > rightx)
{
rb.velocity = new Vector2(0,0);
transform.localScale = new Vector3(1,1,1);
Faceleft = true;
}
}
}
void SwitchAnim()
{
if ( anim.GetBool("jumping"))
{
if (rb.velocity.y < 0.1)
{
anim.SetBool("jumping", false);
anim.SetBool("falling", true);
}
}
if (coll.IsTouchingLayers(Ground) && anim.GetBool("falling"))
{
anim.SetBool("falling",false);
}
}
/*void Death()
{
Destroy(gameObject);
}
public void JumpOn()
{
anim.SetTrigger("death");
}*/
}
此为一种方法,在使用左右边界空物体作为边界时,这种方法会导致系统同时处理过多左右边界的位置数据
因此可以在start中直接获取leftside/rightside.position.x,然后将变量删除,如代码中的注释部分代码所示