初学unity,老师要求上传的一个小游戏。
首先构建出一个场景,类似于以前玩的潜水艇过障碍的模型,使小球通过这些障碍获胜;如图所示:
下面是代码展示(以下代码均为C#)
这是自动摧毁屏障(障碍物)的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoDestoryBarrier : MonoBehaviour {
private void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
}
}
这是控制障碍物的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BarrierControl : MonoBehaviour {
public GameObject player;
public GameObject BarrierPre;
public GameObject CurrentBarrier;
public int BarrierInterval = 10;
void Start () {
}
void Update () {
AutCreatBarrier();
}
public void AutCreatBarrier()
{
if(player.transform.position.x>CurrentBarrier.transform.position.x)
{
//生成新的障碍物
float targetX = CurrentBarrier.transform.position.x+BarrierInterval;
float targetY = RandomBarrierPositionY();
Vector3 targetPos = new Vector3(targetX,targetY,0);
GameObject g = Instantiate(BarrierPre,targetPos,Quaternion.identity);
g.transform.localScale = new Vector3(g.transform.localScale.x, RandomBarrierSizeY((int)g.transform.position.y),g.transform.localScale.z);
CurrentBarrier = g;
}
}
public float RandomBarrierSizeY(int y)
{
int yAbs = Mathf.Abs(y);
if(yAbs==0)
{
return 6;
}
else
{
return (3 - yAbs) * 2 - 1;
}
}
public float RandomBarrierPositionY()
{
int r = Random.Range(-3,3);
return r;
}
}
这是控制相机移动的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraControl : MonoBehaviour {
public GameObject player;
private float offset_camera;
void Start () {
offset_camera = gameObject.transform.position.x - player.transform.position.x;
}
// Update is called once per frame
void Update () {
FollowCameraMove();
}
void FollowCameraMove()
{
gameObject.transform.position = new Vector3(offset_camera + player.transform.position.x, gameObject.transform.position.y,gameObject.transform.position.z);
}
}
这是控制小球移动(通过w、s、a、d控制小球移动)的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playMove : MonoBehaviour {
public Rigidbody rd;
public float speedAutoMove = 5;
public float speedMoveUpandDown = 20;
void Start () {
rd = gameObject.GetComponent<Rigidbody>();
}
void Update () {
PlayerAutoMove();
PlayerMoveUpandDown();
}
private void PlayerAutoMove()
{
rd.AddForce(Vector3.right*speedAutoMove);//前进
}
private void PlayerMoveUpandDown()
{
float v = Input.GetAxis("Vertical");//上下运动
rd.AddForce(v*Vector3.up*speedMoveUpandDown);//给一个上下的力量
}
}
这是控制墙的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wallControl : MonoBehaviour {
private float offset;
public GameObject player;
// Use this for initialization
void Start () {
offset = gameObject.transform.position.x - player.transform.position.x;
}
// Update is called once per frame
void Update () {
FollowPlayerMove();
}
void FollowPlayerMove()
{
gameObject.transform.position = new Vector3(player.transform.position.x+offset,0,0);
}
}
运动效果:
不喜勿喷,谢谢