边学边练Unity—小球demo
从零开始Unity3D—小球demo
首先我们导入建好的场景模型并为其添加碰撞盒,模型是在3DMAX中建的,在unity中为其添加了材质球。
添加小球,为其添加刚体,添加材质球
添加小方块,这里为了方便只做了三个(这里可以直接复制黏贴,C和V按起来),并为其更改tag,我为其命名为f
添加一个Text用来显示分数,记得把里面文字删掉哦
接下来上代码:在这里我实现了方块的旋转,小球碰撞方块后方块消失且每次碰撞后小球随机改变颜色,计分器。
我们先来看看运行效果图吧
小方块的旋转:
using UnityEngine;
using System.Collections;
public class ft : MonoBehaviour {
public Space rotateSpace;
// Use this for initialization
void Start () {
}
void Update () {
transform.Rotate (new Vector3 (10, 0, 0), rotateSpace);
//transform.Rotate (new Vector3 (0, 10, 0), rotateSpace);
//transform.Rotate (new Vector3 (0, 0, 10), rotateSpace);
}
}
控制小球运动:
public float movespeed=10.0f;
void Update () {
if (Input.GetKey (KeyCode.W)) {
this.gameObject.transform.Translate(new Vector3(0,0,movespeed *Time.deltaTime),this.gameObject.transform);
}
if (Input.GetKey (KeyCode.A)) {
this.gameObject.transform.Translate(new Vector3(-1*movespeed *Time.deltaTime,0,0),this.gameObject.transform);
}
if (Input.GetKey (KeyCode.S)) {
this.gameObject.transform.Translate(new Vector3(0,0,-1*movespeed *Time.deltaTime),this.gameObject.transform);
}
if (Input.GetKey (KeyCode.D)) {
this.gameObject.transform.Translate(new Vector3(movespeed *Time.deltaTime,0,0),this.gameObject.transform);
}
}
碰撞方块消失,小球随机颜色,计分器:
public Text scoreText;
private int score=0;
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "f") {
Destroy(collision.collider.gameObject);
score++;
this.gameObject.GetComponent<MeshRenderer>().material.color = RandomColor();
scoreText.text="Score "+score;
}
}
public Color RandomColor()
{
float r=Random.Range(0f,1f);
float g=Random.Range(0f,1f);
float b=Random.Range(0f,1f);
Color color=new Color(r,g,b);
return color;
}
小球demo完成了。