见缝插针
导入图片圆资源
创建2D精灵命名为Rotater并将图片添加给2D精灵Sprite属性,并将图片颜色改为黑色,
(在此之前可以更改相机的背景颜色BackGround属性,以此游戏画面更加漂亮)
在此期间需要更改圆的大小以此来防止圆插上针以后针被顶出屏幕。
然后在Rotater的属性面板中添加ScriptC#脚本一定要是C#语言的脚本并在脚本中写下以下代码
园旋转代码
public class Rotation: MonoBehaviour
{
public float speed = 90f;//如果想让圆反向旋转的话将90F变成-90F即可,如果旋转速度过快将数值变小即可
void Start()
{
}
void Update()
{
transform.Rotate(0f, 0f, speed*Time.deltaTime);//圆旋转动
}
}
针可以自行制作也可以使用成品模型
针头代码(pin)
public class pin : MonoBehaviour
{
public float speed = 10f;
private Rigidbody2D rg;
// Start is called before the first frame update
void Start()
{
rg=GetComponent<Rigidbody2D>();
rg.velocity = Vector2.up * speed;//针向前移动
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag=="rocat")
{
rg.velocity = Vector2.zero;//清零
Score.scoreValue++;//分数累加
transform.SetParent(collision.transform);//针跟随旋转
}else if(collision.tag=="pin"){
GameObject.FindObjectOfType<GM>().GameOver();//游戏结束
}
}
}
创建针头(pin)和针尾(pinhaed)
将创建好的针实例化
针头实例化代码
public class spend : MonoBehaviour
{
public GameObject pinprefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))//检测鼠标
{
SpawnPin();
}
}
void SpawnPin()
{
Instantiate(pinprefab, transform.position, transform.rotation);//实例化针
}
}
创建UI文本框并调整文本框位置,在文本框中挂载代码
分数显示代码
public class Score : MonoBehaviour
{
public static int scoreValue;
public Text scoreText;
// Start is called before the first frame update
void Start()
{
scoreValue = 0;//初始数字为0
}
// Update is called once per frame
void Update()
{
scoreText.text = scoreValue.ToString();//分数显示
}
}
见缝插针整体主要代码
GameManger代码(MG)
using UnityEditor.SceneManagement;
public class GM : MonoBehaviour
{
private bool isGameOver = false;
public spend spend;
public Rotation rotation;
// Start is called before the first frame update
void Start()
{
}
public void GameOver()
{
if(!isGameOver)//判断游戏结束
{
isGameOver = true;
spend.enabled = false;
rotation.enabled = false;
GetComponent<Animator>().SetTrigger("Gameover");//调用结束动画
}
}
public void RestarOver()
{
EditorSceneManager.LoadScene(EditorSceneManager.GetActiveScene().name);//调用原始界面
}
// Update is called once per frame
void Update()
{
}
}