unity:Enemy的简单移动

代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FrogController : MonoBehaviour
{
    private float speed;
    public Rigidbody2D rb;
    public Transform leftpoint, rightpoint;
    public float leftx;
    public float rightx;
    private bool faceLeft;
    // Start is called before the first frame update
    void Start()
    {
        faceLeft = true;
        speed = 5f;
        rb = GetComponent<Rigidbody2D>();
        transform.DetachChildren();
        leftx = leftpoint.position.x;
        rightx = rightpoint.position.x;

        Destroy(leftpoint.gameObject);
        Destroy(rightpoint.gameObject);
    }

    // Update is called once per frame
    void Update()
    {
        Movement(); 
    }
    private void Movement()
    {
        if (faceLeft)
        {
            rb.velocity = new Vector2(-speed, rb.velocity.y);
            if (transform.position.x <= leftx)
            {
                transform.localScale = new Vector3(-1, 1, 1);
                faceLeft = false;
            }
        }
        else
        {
            rb.velocity = new Vector2(speed, rb.velocity.y);
            if (transform.position.x >= rightx)
            {
                transform.localScale = new Vector3(1, 1, 1);
                faceLeft = true;
            }
        }
    }
}

原理:
给enemy设置两个空的子对象作为左右移动的极限位置。运行时用变量保存左右对象的x值然后分离子对象并销毁。

图片默认为左,所以当面向左的时候以-speed移动,当enemy的x小于左边极限距离是设置转向(localScale),然后向右同理

知识点:

transform.DetachChildren();

分离对象身上的所有子物体

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值