zoukankan      html  css  js  c++  java
  • Unity 3D 一个简单的角色控制脚本

    之所以写这个脚本,是因为我想起了我还是新手的时候,那时为了一个角色控制脚本百度了半天还是一无所获,因为看不懂啊,都写的太高级了

    希望这个脚本能够帮助那些 像曾经的我一样迷失于代码中的新手们能够清晰的理解这个角色控制的含义

     1 ///角色控制脚本
     2 
     3 public class Player : MonoBehaviour {
     4 
     5 public float m_speed=1;   //这个是定义的玩家的移动速度  之所以Public是因为为了方便对其进行调节  (public的属性和对象会在Unity中物体的脚本选项中显示出来  前提是你把脚本挂在了物体上)
     6 
     7 void Update ()   //这个是刷新的意思   以帧为单位的大概每刷新一次1/20秒
     8 
     9 {
    10 
    11         float movex = 0;   //这个代表的是玩家在x轴上的移动
    12 
    13         float movez = 0;   //这个代表的是玩家在z轴上的移动
    14 
    15         if (Input.GetKey(KeyCode.W))   //这个意思是"当按下W键时"
    16 
    17         {
    18 
    19             movez += m_speed * Time.deltaTime;   //物体获得在z轴方向上的增量   也就是向前
    20 
    21         }
    22 
    23         if (Input.GetKey(KeyCode.S))   //按下S键时
    24 
    25         {
    26 
    27             movez -= m_speed * Time.deltaTime;   //
    28 
    29         }
    30 
    31         if (Input.GetKey(KeyCode.A))   //A键
    32 
    33         {
    34 
    35             movex -= m_speed * Time.deltaTime;    //
    36 
    37         }
    38 
    39         if (Input.GetKey(KeyCode.D))   //D键
    40 
    41         {
    42 
    43             movex += m_speed * Time.deltaTime;   //
    44 
    45         }
    46 
    47         this.transform.Translate(new Vector3(movex,0,movez));   //这句代码是把得到的偏移量通过translate(平移函数)给玩家  从而使得玩家的位置得到改变
    48 
    49    } }

    附上玩家的坐标轴  图中飞机就是玩家  便于理解x轴z轴对玩家移动方向的影响

    同时附上Translate函数的圣典介绍:

    Transform.Translate 平移

     

    function Translate (translation : Vector3, relativeTo : Space = Space.Self) : void

    Description描述

    Moves the transform in the direction and distance of translation.

    移动transform在translation的方向和距离。

    简单的说,向某方向移动物体多少距离。

    If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.

    如果relativeTo留空或者设置为Space.Self,移动被应用相对于变换的自身轴。(当在场景视图选择物体时,x、y和z轴显示)如果相对于Space.World 移动被应用相对于世界坐标系统。

     

    using UnityEngine;
    using System.Collections;
    
    public class example : MonoBehaviour {
    	void Update() {
    		transform.Translate(Vector3.forward * Time.deltaTime);
    		transform.Translate(Vector3.up * Time.deltaTime, Space.World);
    	}
    }
  • 相关阅读:
    图书馆管理系统
    php js_unescape correspond to js escape
    咖啡小驻搬家到此,感谢您继续关注本博
    OO系统分析员之路用例分析系列(1)什么是用例
    jquery tab 潇湘博客
    双色球中奖查询程序
    大象Thinking in UML早知道 001公告
    魔摸新学堂简介
    拙著《大象Thinking in UML》已在互动出版网http://www.chinapub.com/129881开始出售,12月1日全国各大书店有售,敬请关注!^_^
    jQuery进入微软和Nokia的解决方案 潇湘博客
  • 原文地址:https://www.cnblogs.com/qiaogaojian/p/5868561.html
Copyright © 2011-2022 走看看