您的位置:首页 > 移动开发 > Unity3D

Unity_2D游戏对象的移动_075

2017-09-02 11:46 363 查看
通过前面对创建动画帧的学习,我们结合脚本让游戏对象移动起来此时用的是一个天鹅飞行的效果。

在精灵上绑定此脚本:

using UnityEngine;
using System.Collections;

public class SwanMove : MonoBehaviour {

public float speed;

private float width;
private float height;
private Vector3 startposition;
// Use this for initialization
void Start () {
//计算精灵自身的尺寸大小
width = transform.GetComponent<Renderer>().bounds.extents.x;
height = transform.GetComponent<Renderer>().bounds.extents.y;
transform.position = new Vector3(0 + width,0,0);
//将屏幕坐标系转化成世界坐标系
Vector3 moveWidth = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0));
startposition = new Vector3(moveWidth.x + width, 0, 0);
//把天鹅放在起始位置
transform.position = startposition;
}

// Update is called once per frame
void Update () {
//如果精灵在屏幕内移动
if (transform.position.x>-startposition.x)
{
transform.Translate(Vector3.right * -speed * Time.deltaTime);
}
else
{
//如果精灵超出屏幕的边界 那么就重新置为起始位置
transform.position = startposition;
}
}
}


效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: