unity C#游戏脚本基础

//控制生成物体移动
using
System.Collections; using System.Collections.Generic; using UnityEngine; public class shoot : MonoBehaviour { // Start is called before the first frame update public GameObject bullet; //定义物体,需要把库里的物体拖到bullet上当作bullet public float speed = 5;//定义速度 ,public变量可以在unity界面实时修改 void Start() { Debug.Log("hello"); //日志界面输出 } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) //鼠标左键点击 { GameObject b = GameObject.Instantiate(bullet, transform.position, transform.rotation); //初始化生成物体,(后两个变量表示在本物物体位置生成)(相机) Rigidbody rgd = b.GetComponent<Rigidbody>(); //获得物体的物理属性 rgd.velocity = transform.forward * speed; // 给物体施加向前的速度 forword } } }
//控制当前脚本所在物体移动
using
System.Collections; using System.Collections.Generic; using UnityEngine; public class move : MonoBehaviour { // Start is called before the first frame update public float speed = 3; void Start() { } // Update is called once per frame void Update() { float h = Input.GetAxis("Horizontal"); //获得横向移动数据 X轴 // Debug.Log(h); float v = Input.GetAxis("Vertical"); // 获得纵向移动数据 Y轴 // WASD控制 或者上下左右 transform.Translate(new Vector3(h, v, 0)*Time .deltaTime*speed); //deltatime和帧数有关,每次乘上deltatime就可以忽略帧数变化了,再乘上你定义的speed //具体: 比如你是60帧,你键盘IO了一下,会移动非常多,因为很多帧都接收到了键盘IO,这时候60帧的deltatime就是1/60,所以乘上之后可以忽略 } }
原文地址:https://www.cnblogs.com/acmLLF/p/14610096.html