您的位置:首页 > 移动开发 > Unity3D

Unity官方实例教程 Roll-a-Ball

2017-05-17 14:53 417 查看
与unity的transform组件相处的挺久了,最近项目不太忙,决定好好打下unity的基础。那么从Roll-a-Ball这个简单游戏开始吧!1.先创建一个球体游戏对象,改名为Player,transform值y=0.5,加上刚体组件,具体如下图:其中脚本PlayerController.cs代码如下:
using UnityEngine;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{

public float speed;
public Text countText;
private float count;

// Use this for initialization
void Start ()
{
count = 0;
setCountText();
}

// Update is called once per frame
void FixedUpdate ()
{

float moveH = Input.GetAxis("Horizontal");
float moveV = Input.GetAxis("Vertical");
Vector3 move = new Vector3(moveH,0.0f,moveV);
GetComponent<Rigidbody>().AddForce(move * speed * Time.deltaTime);

}

void OnTriggerEnter(Collider other)
{
Debug.Log("碰撞");
if (other.gameObject.tag == "PickUp")
{
other.gameObject.SetActive(false);
count++;
setCountText();
}
}

private void setCountText()
{
countText.text = "Count:" + count;
}
}
2.创建一个平面,改名为Ground,具体如下图:3.摄像机,让相机简单跟随游戏对象,为Main Camera挂一个脚本CameraController,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour
{

public GameObject player;

private Vector3 offset;

// Use this for initialization
void Start ()
{
offset = transform.position;
}

// Update is called once per frame
void LateUpdate ()
{
transform.position = offset + player.transform.position;
}
}
4.创建被抓取的立方体,通过预制体来做,先创建一个立方体,transform中rotation三个值都设为45,挂上脚本Rotator,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotator : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
transform.Rotate(new Vector3(15,30,45) * Time.deltaTime);
}
}
然后将这个cube拖到Assets下面预制体文件夹中,再通过这个预制体来创建多个。6.再简单的添加一个计分板,create-UI-Text,并拖拽到Player的countText参数下,调整合适位置
Ground加墙什么的可以自由发挥,都比较简单。。。

比较重要的是理解Rigidbody,Collider,Is Trigger这三个东西,具体看这个总结:http://blog.csdn.net/monzart7an/article/details/22739421


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: