一、过程总结
(一)搭建场景
1、创建新项目——2D。
2、新建文件夹Sprites用于存放所需素材。
3、将ground拖入scene并根据图片进行分辨率的设置。
4、调整摄影机size。
5、新建空物体Map,将ground和Hole作为Map的子物体,并将Hole的Order in Layer 值设置为1,ground的Order in Layer为0,确保Hole在ground上层显示。
6、保存场景为s1。
(二)制作地鼠
1、添加地鼠素材Gophers和Gophers_Beaten,并添加Box Collider 2D。
2、在Gophers上添加脚本Click,Gophers_Beaten上添加脚本Disappear,用于控制单击地鼠后的效果。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Click : MonoBehaviour {
public GameObject mouse2;
void Start () {
}
void OnMouseDown() {
Instantiate(mouse2,transform.position,Quaternion.identity);//当前位置生成mouse2
Destroy(gameObject);//点击销毁
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Disappear : MonoBehaviour {
void Start () {
Destroy(gameObject,0.5f);
}
void Update () {
}
}
3、将Gophers和Gophers_Beaten作为预制体。
4、新建脚本CreateTarget用来控制地鼠的随机生成。将脚本添加至空物体CreateTarget。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateTarget : MonoBehaviour {
public GameObject mouse1;
void Start () {
InvokeRepeating("Create",0,1);
}
void Create() {
Vector3 pos = Vector3.zero;
int id = 0;
id = Random.Range(0, 9);//产生随机数
switch (id) {
case 0:
pos = new Vector3(-2,1,0);
break;
case 1:
pos = new Vector3(-2,0, 0);
break;
case 2:
pos = new Vector3(-2,-1, 0);
break;
case 3:
pos = new Vector3(0,1, 0);
break;
case 4:
pos = new Vector3(0,0, 0);
break;
case 5:
pos = new Vector3(0,-1, 0);
break;
case 6:
pos = new Vector3(2,1, 0);
break;
case 7:
pos = new Vector3(2,0, 0);
break;
case 8:
pos = new Vector3(2, -1, 0);
break;
}
Instantiate(mouse1,pos,Quaternion.identity);
}
void Update () {
}
}
5、添加声音appear给预制体Gophers,beaten给预制体Gophers_Beaten。
(三)分数设置
1、添加UI——Text,设置Text位置、大小、颜色等信息。
2、新建Score脚本,对分数进行设置。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour {
public static int score;
Text text;
void Start () {
text = GetComponent<Text>();
score = 0;
}
void Update () {
text.text = "Score:" + score;
}
}
3、在Disappear脚本中添加有关分数的语句。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Disappear : MonoBehaviour {
int scoreValue = 10;
void Start () {
Destroy(gameObject,0.5f);
Score.score += scoreValue;
}
void Update () {
}
}
(四)完成
二、收获总结
1、3D物体自带Box Collider,而2D物体则需要自行添加Box Collider 2D方可使用;
2、利用 InvokeRepeating函数实现了地鼠出现位置的随机生成;
3、地鼠出现后若不打击,地鼠不会在一段时间内自动消失;(不足)
4、在同一位置已经出现地鼠,并且在还未击打的情况下仍会重叠出现地鼠。(不足)