新建鸟对象精灵 : New 2D object Sprite
实现:按键后向上移动
刚体 : Rigidbody 2D
重量规模参数 : gravity scale
Update() : 是每一帧要执行的代码
//实现:按键后向上移动
//向上的力 给到 组件-->刚体
public class liao : MonoBehaviour
{
Rigidbody2D rg;
public float upForce = 200f;
// Start is called before the first frame update
void Start()
{
rg = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
rg.AddForce(Vector2.up * upForce);
}
}
}
实现:自动向左移动
组件 :Component
刚体 :Rigidbody
变换 :Transform
坐标 :Vector
//实现:自动向左移动
public class zhanAiYiDong : MonoBehaviour
{
public float speed = 2f;
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
}
实现:碰撞加分or结束
方框碰撞体 :Box Collider 2D
多边形碰撞体 : Polygon Collider 2D
public class zhanAiYiDong : MonoBehaviour
{
public float speed = 2f;
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.left * speed * Time.deltaTime);
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
Debug.Log("+1");
//score +1 ;
}
}
}
实现:障碍自动生成
产卵点 : spawnpoint
public class spawn : MonoBehaviour
{
public GameObject zhangAi; //定义生成的对象,这个参数需要在unity里面赋值。
public float colddown = 2f;
float nextSpawn;
// Update is called once per frame
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + colddown; //每隔2秒生成一个障碍
Vector3 spawnP = transform.position; //生成障碍的位置
spawnP.y += Random.Range(-3f, 3f); //生成障碍的位置调整
Instantiate(zhangAi, spawnP, transform.rotation); //实际生成障碍
}
}
}
实现: GM记录游戏数据
public class GM : MonoBehaviour
{
public static int score = 0;
public static bool isActive = true;
}
实现: 碰撞大地和障碍后游戏停止
public class shutdown : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "Player")
{
GM.isActive = false;
}
}
}