创建模型
1.创建小球
在Hierarchy中创建一个小球(右键点击3D Object中的Sphere),在Inspector中点击添加组件 (Add Component) 增添小球碰撞体(Box Collider)和刚体(Rigidbody)。
2.创建地面
在3D Object中添加地面(Plane)并为地面添加上碰撞体,
调整地面为合适大小(默认即可)。
3.创建食物
在3D Object中添加立方体(Cube)命名为Food并为立方体添加上相应的碰撞体。在Project中创建立方体的预制体(Profabs)并放在文件夹中。
将Inspector中的立方体复制多个(ctrl+D或选中目标右键点击Paste)作为小球的食物,创建预制体。
创建墙壁
创建墙壁的方法与创建食物的方法相同,不同的是需要调整墙壁的大小
在每个物体中都有Transform其中Scale可以调整物体的长,宽,高(x,y,z)。
编写代码
小球的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class script : MonoBehaviour
{
public int score = 0;
public Text text;
public GameObject winText;
public GameObject lostText;
public Wallscript wallscript;
public Rigidbody body;/// <summary>
/// 声明一个组件
/// </summary>
// Start is called before the first frame update
void Start()
{
//Debug.Log("开始游戏了!");
body = GetComponent<Rigidbody>();
//得到一个组件,<>内为组件名
}
// Update is called once per frame
void Update()
{
Debug.Log("游戏正在运行!");
float i = Input.GetAxis("Horizontal"); //Horizontal左右键
float j = Input.GetAxis("Vertical");//Vertical前后
body.AddForce(new Vector3(i,0,j)*3);
}
private void OnCollisionEnter(Collision collision) //判断是否发生碰撞OnCollisionEnter是碰撞的瞬间
{
if (collision.gameObject.tag == "Cube") //collision.gameObject获得标签
{
//Destroy(collision.gameObject); //Destroy毁坏物体
lostText.SetActive(true);
}
}
private void OnTriggerEnter(Collider other)//触发区域检测
{
if (other.tag == "Food")
{
Destroy(other.gameObject);
score++;
text.text = "分数:"+score; //显示分数
if(score==7)
{
winText.SetActive(true); //激活对象
}
}
}
}
食物的代码(立方体)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class foodscript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Rotate(Vector3.up);
// transform.Rotate(Vector3.back);
//将物体旋转Rotate是旋转()内是旋转方向
}
}
相机跟随小球运动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class follwtarge : MonoBehaviour
{
public Transform tf; //transform位置
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - tf.position;
//两物体的位置之差
}
// Update is called once per frame
void Update()
{
transform.position = tf.position + offset;
}
}
游戏打包
点击左上角的File,找到Building Settings,添加场景(Add Open Scense)可以选择Pc端,iOS端,Android端。
最后点击Build,选择打包位置。