Unity_2D游戏对象的移动_075

来源:互联网 发布:科比nba数据统计 编辑:程序博客网 时间:2024/05/17 00:55

通过前面对创建动画帧的学习,我们结合脚本让游戏对象移动起来此时用的是一个天鹅飞行的效果。
在精灵上绑定此脚本:

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;        }    }}

效果如下:
这里写图片描述