学习untiy最最基础简单的实例,是看泰课的入门视频。
一直觉得,最好的学习方法,要把别人的东西,变成自己的东西,最简单的几行代码也可以学到很多东西。这个工程就是按照视频上做的,找不到素材,随便自己做了几个材质,做了几个prefab来凑数。
一、方块的prefab:
using UnityEngine;
using System.Collections;
public class BrickBall : MonoBehaviour {
public GameObject cube;
public int column =10; // 列数
public int row = 5; // 行数
// Use this for initialization
void Start () {
print("it begin.");
// Instantiate(cube);
for (int j =0; j < row; j++){
for (int i = 0; i < column; i++)
{
Instantiate(cube, new Vector3(i, 0.5f+j*1, 0), Quaternion.identity);
}
}
}
// Update is called once per frame
void Update () {
}
}
二、发射的子弹的prefab:
这个脚本挂在了MainCamera,子弹从我们的摄像头发出。
using UnityEngine;
using System.Collections;
public class shooter : MonoBehaviour {
public Rigidbody bullet;
public GameObject shootPos;
public float force = 1000;
public float movespeed = 1000;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1")) {
Rigidbody ball = Instantiate(bullet, shootPos.transform.position, Quaternion.identity) as Rigidbody;
ball.AddForce(shootPos.transform.forward * force);
}
// GetButtonDown检查键盘有没有按下
//if (Input.GetButtonDown("Horizontal"))
if (Input.GetButton("Horizontal")) // 连续按键的情况
{
// GetAxis()返回按下的键是虚拟映射命令的方向是正向还是负向。正向返回正值,负向返回负值。
// 值的大小有随机性。
//print(Time.deltaTime);
print(Input.GetAxis("Horizontal"));
// 在电脑上调试的时候,Time.deltaTime基本是0.016左右,这个值是帧更新所用的时间,与平台有关。
// 这里乘以一个Time.deltaTime是为了让速度变小。如果我本身设置就不大,就没必要乘。
// 想要移动平滑,只要使用GetButton来处理按键hold的情况即可。
// 但是这里要考虑,GetAxis返回值也是随机性的,电脑上基本是0.05左右,偏差不会太大。
float h = Input.GetAxis("Horizontal")*movespeed;
// GetButton("Horizontal")下垂直方向上肯定是0
// float v = Input.GetAxis("Vertical")*movespeed*Time.deltaTime;
transform.Translate(h, 0, 0);
}
if (Input.GetButton("Vertical"))
{
float v = Input.GetAxis("Vertical") * movespeed;
transform.Translate(0, v, 0);
}
{
}
}
}
三、销毁子弹的代码:
这里代码其实很简单,只不过我自己想当然试了下直接Destroy(this),把this所指代的东西没有分清楚。
using UnityEngine;
using System.Collections;
public class Destroy : MonoBehaviour
{
// Use this for initialization
void Start()
{
// this代指这个类,也就是Destroy,gameObject是这个类关联的游戏物体。
// Destroy(this,2); // 错误代码。
Destroy(this.gameObject, 2);
}
// Update is called once per frame
void Update()
{
}
}
以上,代码就这些,简单的小例子,不需要素材,全部都可以很容易地现做的。
其实之前已经陆陆续续学了些实例,但是少有这样非常仔细地学习API的用法,这个作为一个开始,与君共勉。