霸气的昵称 发表于 2012-12-14 23:55

让GameObject保持预订速率向前移动的脚本

还是一篇41post的翻译,对于老鸟们可能就没用了,这个脚本太简单了,但是小小鸟们可以看看,或许有点用能,希望大家喜欢!!!
    下面正文:
这个Unity编程教程将展示如何创建一个让GameObject保持预订速率向前移动的脚本。这个油门速率控制器可以应用在像船,飞机,火车上。照例,Unity工程文件会在文章的结尾提供下载。
本教程的灵感来自于半条命,有一辆玩家可以驾驶的列车,你们可能已经不怎么记得了,来看看这张截图:



下面这段代码也可以做到如此。来看看代码:using UnityEngine;
using System.Collections;

public class ThrottleController : MonoBehaviour
{
//The game object's Transform
private Transform goTransform;
//the throttle increment to the current velocity
private float increment=0.0f;
//this variable stores the vertical axis values
private float vertAxis=0.0f;
//the throttle
private float throttle =0.0f;

void Awake ()
{
//get this game object's Transform
goTransform = this.GetComponent<Transform>();
}

void Update ()
{
//Get the vertical input value and store it at the vertAxis variable
vertAxis = Input.GetAxis("Vertical");

//change the 'increment' value based on the vertical input
if(vertAxis>0)
{
increment = 0.05f;
}
else if(vertAxis<0)
{
increment = -0.05f;
}

//after releasing the vertical axis, add the increment the throttle
if(Input.GetButtonUp("Vertical"))
{
throttle = throttle+increment;
}

//set the throttle limit between -0.05f (reverse) and 0.25f (max speed)
throttle=Mathf.Clamp(throttle, -0.05f,0.25f);

//translates the game object based on the throttle
goTransform.Translate(throttle * Vector3.forward);

//rotates the game object, based on horizontal input
goTransform.Rotate(Vector3.up * Input.GetAxis("Horizontal"));
}
}
实质上,这个脚本是检查垂直轴的按钮是否被按下和释放。然后,将增量加上垂直输入的值加上添加的油门变量设置为使GameObject移动的速率。这是核心内容。
首先要声明goTransform为Transform变量(例如第7行),之后在代码中存储GameObject的Transform将被用到。下面,我们有3个浮点数被声明并初始化:
   increment ,改变油门的值。
   vertAxis,存储键盘输入结果,在1到-1之间
   throttle,GameObject的移动速率(例如第10,12,14行)
然后,在Awake()方法中有一行初始化goTransform的代码(例如19行)。剩下的都在Update()方法中运行。
verAxis变量就是垂直轴输入的值(例如25行)。使用if-else语句来判断verAxis是正还是负,如果为正,increment就被设置为0.05f,如果为负,increment就等于-0.05f(例如第28到35行)。
最后一个if语句在垂直输入按钮被释放时,把increment值加到throttle变量。(例如第38到41行)。使用第44行代码,玩家可以更好的控制油门,不会直接到最大值或最小值。因为throttle是以0.05为基数改变的,在-0.05到0.25f的范围内都是可以的,并且有5个不同速度可以控制GameObject向前移动。
就是这些了,别忘了评论啊!!!

Unity工程下载:
http://www.41post.com/uploads/files/throttlecontroller.zip
英文源地址 :
http://www.41post.com/4073/programming/unity-throttle-controller

skyangel 发表于 2012-12-15 20:43

嗯 不错哦 么么哒

Spinach 发表于 2013-1-31 09:48

老鸟路过 。。。。。

st闪光弹 发表于 2017-2-9 10:31

真心顶

7759367 发表于 2017-2-9 10:45

难得一见的好帖

dilly123 发表于 2017-2-9 11:19

说的非常好

1011shl 发表于 2017-2-9 10:30

很好哦

mice714 发表于 2017-2-9 10:27

LZ真是人才

wozhizhizhi 发表于 2017-3-20 15:58

很不错

大强 发表于 2017-3-20 15:24

好帖就是要顶
页: [1]
查看完整版本: 让GameObject保持预订速率向前移动的脚本