关于unity2D中简单敌人的相关代码及操作

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,然后将变量删除,如代码中的注释部分代码所示

本代码仍然存在问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值