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

Unity游戏开发的数学与物理 1 ( 物体延水平方向运动 )

2015-04-21 23:11 906 查看
物体延水平方向运动

工程实现需注意:

- 摄像机的设置 Projection Orthographic

- Start() 和 Update()的执行顺序与执行次数

- 屏幕坐标与空间坐标的转换

- 关于Time.deltaTime

- x += v; v = -v;

using UnityEngine;
using System.Collections;

//匀速运动
public class UnirormMotionTest : MonoBehaviour
{
//物体的位置
float posX = 0;

//物体在x方向上的速度
float speed = 3;

//屏幕的右上像素在世界空间的坐标
Vector3 ScreenRightTopPos;

//屏幕的左下像素在世界空间的坐标
Vector3 ScreenLeftBottomPos;

//box的半宽度
float boxHalfWidth;

//屏幕坐标的示意图
//+-----------+(Screen.width, Screen.height)
//|           |
//|  screen   |
//|           |
//+-----------+
//(0, 0)

void Start()
{
//将屏幕右上的像素转换为世界空间的坐标
ScreenRightTopPos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0));

//将屏幕右下的像素转换为世界空间的坐标
ScreenLeftBottomPos = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0));

//box的半宽度
boxHalfWidth = transform.localScale.x * 0.5f;
}

void Update ()
{
if (transform.localPosition.x + boxHalfWidth > ScreenRightTopPos.x
|| transform.localPosition.x - boxHalfWidth < ScreenLeftBottomPos.x)
{
//改变方向
speed = -speed;
}

posX += speed * Time.deltaTime;

transform.localPosition = new Vector3(posX, 0.5f, 0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  游戏开发 unity