边学边练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完成了。

工程文件:https://download.csdn.net/download/qq_41065100/12401500

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值