Unity2D小游戏——类似QQ堂的小 demo(炸弹人)
一 : 语言 :C# 点击这里下载项目工程
二 : 涉及到的功能:
1.主角,上下左右移动
2.主角,放置炸弹
3.炸弹可以销毁某些砖块,敌人
4.通过射线检测,实现敌人随机运动
三:效果图(游戏中用到的图片来源于网络,侵删)
四 :代码
(1),主角移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
private Rigidbody2D rigidbody2D;
private Animator anim;
public float speed = 10f;
private void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
private void FixedUpdate()
{
float h = Input.GetAxisRaw("Horizontal");//键值对
float v = Input.GetAxisRaw("Vertical");
GetComponent<Rigidbody2D>().velocity = new Vector2(h, v) * speed;//方向*速度
GetComponent<Animator>().SetInteger("X", (int)h);//X轴方向上动画
GetComponent<Animator>().SetInteger("Y", (int)v);//Y轴方向上动画
}
}
(2),主角放置炸弹
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BombDrop : MonoBehaviour {
public GameObject BombPrefab;
void Update () {
Vector2 pos = transform.position;//炸弹的位置
if(Input.GetKeyDown(KeyCode.Space))
{
Instantiate(BombPrefab, pos, Quaternion.identity);//实例化预制体
}
}
}
(3)炸弹 一定时间后销毁
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BombAfter : MonoBehaviour {
public GameObject ExplosionPrefab;
public float time = 1.5f;
void Start () {
Destroy(gameObject, time);
}
}
(4)炸弹爆炸
即从 到
的过程:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bomb : MonoBehaviour {
public GameObject ExplosionPrefab;
private void OnDestroy() //炸弹被销毁时调用
{
Instantiate(ExplosionPrefab, transform.position, Quaternion.identity); //实例化生成爆炸后的炸弹的样子
}
}
(5) 一定时间后销毁
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroy : MonoBehaviour {
public float time = 1f;
void Start () {
Destroy(gameObject, time);
}
}
(6) 炸弹爆炸,可以销毁,某些砖块,敌人,以及主角 (除了不可被销毁的砖块,其他的都可被销毁)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour {
private void OnTriggerEnter2D(Collider2D col)
{
if (!col.gameObject.isStatic) //只要是非静态,就可被炸弹销毁
{
Destroy(col.gameObject);
}
}
}
注意:不可被销毁的砖块打上勾
(7) 敌人随机方向移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Worm : MonoBehaviour {
public float speed = 2f;
Vector2 RanDir()
{
int r = Random.Range(-1, 2);
return (Random.value < 0.5 ? new Vector2(r, 0): new Vector2(0,r));
}
bool isValidDir(Vector2 dir)
{
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider.gameObject);
}
void ChangeDir()
{
Vector2 dir = RanDir();
if (isValidDir(dir))
{
GetComponent<Rigidbody2D>().velocity = dir * speed;
GetComponent<Animator>().SetInteger("X", (int)dir.x);
GetComponent<Animator>().SetInteger("Y", (int)dir.y);
}
}
void Start () {
InvokeRepeating("ChangeDir", 0, 0.5f);
}
}