• 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);
    	}
    }
  • 相关阅读:
    codeforces 37 E. Trial for Chief【spfa】
    bzoj 1999: [Noip2007]Core树网的核【树的直径+单调队列】
    codehunter 「Adera 6」杯省选模拟赛 网络升级 【树形dp】
    codeforces GYM 100781A【树的直径】
    bzoj 2878: [Noi2012]迷失游乐园【树上期望dp+基环树】
    bzoj 1791: [Ioi2008]Island 岛屿【基环树+单调队列优化dp】
    codeforces 949C
    codeforces 402E
    poj 3613 Cow Relays【矩阵快速幂+Floyd】
    bzoj 2097: [Usaco2010 Dec]Exercise 奶牛健美操【二分+树形dp】
  • 原文地址:https://www.cnblogs.com/qiaogaojian/p/5868561.html
Copyright © 2020-2023  润新知