让青蛙能左右移动,原理是给青蛙添加看不见的空物体,空物体带有位置坐标。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class frog_move : MonoBehaviour
{
Transform leftpoint, rightpoint;
Rigidbody2D rd;
bool faceleft = true;
// Use this for initialization
void Start ()
{
rd = GetComponent<Rigidbody2D>();
leftpoint= transform.GetChild(0);
rightpoint = transform.GetChild(1);
transform.DetachChildren();
}
// Update is called once per frame
void Update ()
{
Move();
}
private void Move()
{
if (faceleft)
{
//向左移动
rd.velocity = new Vector2(-2, rd.velocity.y);
//如果到达左边点
if (transform.position.x<leftpoint.position.x)
{
//转向
transform.localScale = new Vector3(-1, 1, 1);
faceleft = false;
}
}
else
{
rd.velocity = new Vector2(2, rd.velocity.y);
//如果到达右边点
if (transform.position.x > rightpoint.position.x)
{
//转向
transform.localScale = new Vector3(1, 1, 1);
faceleft = true;
}
}
}
}
但是因为空物体和青蛙frog是父子关系,移动青蛙也会移动空物体。
有几个方法来解决。
方法一解除父子关系
只需要在start最后添加上解除父子关系语句。
transform.DetachChildren();
那么空物体与frog也就没有关联性,缺点是会产生大量的gameobject,因为仅仅是取消关系,物体还在。
方法二删除空物体
方法一当有大量frog的时候,解除父子关系会产生大量游戏对象,所以更好的方法是获取了transform之后,删除掉空物体。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class frog_move : MonoBehaviour
{
Transform leftpoint, rightpoint;
Rigidbody2D rd;
bool faceleft = true;
float leftx, rightx;
public float speed = 2f;
// Use this for initialization
void Start ()
{
rd = GetComponent<Rigidbody2D>();
leftpoint= transform.GetChild(0);
rightpoint = transform.GetChild(1);
leftx = leftpoint.position.x;
rightx = rightpoint.position.x;
Destroy(leftpoint.gameObject);
Destroy(rightpoint.gameObject);
}
// Update is called once per frame
void Update ()
{
Move();
}
private void Move()
{
if (faceleft)
{
//向左移动
rd.velocity = new Vector2(-speed, rd.velocity.y);
//如果到达左边点
if (transform.position.x<leftx)
{
//转向
transform.localScale = new Vector3(-1, 1, 1);
faceleft = false;
}
}
else
{
rd.velocity = new Vector2(speed, rd.velocity.y);
//如果到达右边点
if (transform.position.x > rightx)
{
//转向
transform.localScale = new Vector3(1, 1, 1);
faceleft = true;
}
}
}
}
注意leftx和rightx不能省略,因为游戏开始后会删除空物体,如果还是按照以前的语句就会出错:
transform.position.x<leftpoint.position.x
此时没有物体,也就没办法获取leftpoint.position.x