Unity3D 物体运动小游戏
发布日期:2021-06-30 16:33:58 浏览次数:2 分类:技术文章

本文共 2660 字,大约阅读时间需要 8 分钟。

目录


一、在Hierarchy窗口中创建场景,之后塑造一个平面作为地板,将元件命名为background。再创建一个正方体,命名为player。

二、在project窗口中创建两个folder文件夹。一个命名为材料material,一个命名为脚本scripts。

在material文件夹中创建两个material,调整颜色,创建好之后直接拖动到player和background之上。在scripts文件夹中创建C# 脚本文件,命名为playermove。双击脚本文件,在VS中打开。

三、编写playermove移动的代码。

需要在player原件中添加刚体,否则物体不能受力。

接下来在VS中的脚本代码中进行物体移动的编码。然后把playermove脚本拖动到player元件上。点击运行,按下WASD四建就可以对正方体player进行移动操作了。

public class playermove : MonoBehaviour {        public float moveSpeed; //移速	// Use this for initialization	void Start () {		}		// Update is called once per frame	void Update () {        //获取键盘数值        //var 自动匹配目标类型        var move = new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical")); //构建一个向量,获取X,Y,Z三轴的变量        var rigidbody = GetComponent
(); rigidbody.AddForce(move * moveSpeed); //给刚体添加一个力 }}

 

 如果不想让正方体滚动,可以在刚体rigidbody中的Constraints的选项中把Freeze Rotation中的x,y,z全部锁定。物体的移动就会变成平移。

四、设置敌人物体

与创建player方块相同,创建enemy敌人方块。创建一个patrol脚本,将脚本拖动到enemy元件上。打开patrol,进行物体固定轨道移动的编码。

patrol脚本的代码如下: 

public class patrol : MonoBehaviour {    public GameObject[] gameObjectArray; //建一个数组 也可以写作public List
gameObjectList; public int index = 0; //设置数组索引 public float moveSpeed; //移速 // Use this for initialization void Start () { } // Update is called once per frame void Update () { //Update是每帧来计算的,游戏每一帧会运行update一次 //设置物体缓慢移动的方法MoveToward(current/当前的位置,target/目标位置,maxDistanceDelta) //添加了Time.deltaTime是时间增量,渲染完上一帧的时间 transform.position = Vector3.MoveTowards(transform.position,gameObjectArray[index].transform.position,moveSpeed * Time.deltaTime); //这是新的移动位置,把新的位置赋值给position }}

回到unity界面,新建三个空坐标

移动三个位置

 点击enemy,将GameObject拖动到Game Object Array中,可以自己设置Move Speed的速度。

现在只是运行了一次数组中enemy的行动,所以对patrol的代码进行修改,结果如下:

public class patrol : MonoBehaviour {    public GameObject[] gameObjectArray; //建一个数组 也可以写作public List
gameObjectList; public int index = 0; //设置数组索引 public float moveSpeed; //移速 // Use this for initialization void Start () { } // Update is called once per frame void Update () { //Update是每帧来计算的,游戏每一帧会运行update一次 //设置物体缓慢移动的方法MoveToward(current/当前的位置,target/目标位置,maxDistanceDelta) //添加了Time.deltaTime是时间增量,渲染完上一帧的时间 if (index > gameObjectArray.Length-1) //如果索引超出数组下标 { index = 0; } transform.position = Vector3.MoveTowards(transform.position,gameObjectArray[index].transform.position,moveSpeed * Time.deltaTime); //这是新的移动位置,把新的位置赋值给position if (transform.position== gameObjectArray[index].transform.position) //判断,如果地址等于目标地址 { index++; } }}

返回unity3d运行,enemy元件就会循环运动。

 

编写成果:

转载地址:https://kongchengji.blog.csdn.net/article/details/84144912 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JavaScript学习(十三)---RegExp对象
下一篇:JavaScript学习(十二)---正则表达式

发表评论

最新留言

很好
[***.229.124.182]2024年05月04日 14时42分44秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章