在马里奥里有那种自动左右移动的怪,unity中很好实现。
先设置左右范围,为了直观调试范围,创建两个空的gameobject来记录位置。
将位置创建为物体的children,是为了绑定这两个位置和移动物体。可以将frog创建为一个预制体,之后就不用再次创建位置对象。
将位置信息对象赋给script
在脚本中得到边界的x值,得到之后就可以将对象销毁了,因为只关心他的x值
leftx = leftPoint.position.x;
rightx = rightPoint.position.x;
//获取值后可以消除了
Destroy(rightPoint.gameObject);
Destroy(leftPoint.gameObject);
在移动代码中根据位置信息,改变物体的移动状态。
完整代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_frog : MonoBehaviour
{
private Rigidbody2D rb;
public Transform rightPoint, leftPoint;
private bool faceLeft = true;
private float leftx, rightx;
public float speed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
leftx = leftPoint.position.x;
rightx = rightPoint.position.x;
//获取值后可以消除了
Destroy(rightPoint.gameObject);
Destroy(leftPoint.gameObject);
}
// Update is called once per frame
void Update()
{
Move();
}
private void Move()
{
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;
}
}
}
}