用unity写一个跳一跳的游戏代码
时间: 2023-06-12 21:07:07 浏览: 111
以下是一个简单的跳一跳游戏的代码示例,使用Unity引擎和C#语言编写:
```
using UnityEngine;
using UnityEngine.SceneManagement;
public class JumpGame : MonoBehaviour
{
public float jumpForce = 10f; // 跳跃力度
public Rigidbody2D playerRigidbody; // 玩家刚体
public GameObject platformPrefab; // 平台预制体
public float platformSpawnInterval = 1.5f; // 平台生成间隔
public float platformSpeed = 2f; // 平台移动速度
public float platformDestroyX = -10f; // 平台销毁位置
public Transform platformSpawnPoint; // 平台生成点
public GameObject gameOverPanel; // 游戏结束面板
private float lastPlatformSpawnTime; // 上次生成平台时间
private bool isGameOver; // 游戏是否结束
private void Update()
{
if (Input.GetMouseButton(0) && !isGameOver)
{
playerRigidbody.velocity = Vector2.up * jumpForce;
}
}
private void FixedUpdate()
{
if (!isGameOver && Time.time - lastPlatformSpawnTime > platformSpawnInterval)
{
SpawnPlatform();
}
foreach (Transform platform in transform)
{
platform.position -= Vector3.right * platformSpeed * Time.deltaTime;
if (platform.position.x < platformDestroyX)
{
Destroy(platform.gameObject);
}
}
}
private void SpawnPlatform()
{
lastPlatformSpawnTime = Time.time;
GameObject platform = Instantiate(platformPrefab, platformSpawnPoint.position, Quaternion.identity, transform);
platform.transform.localScale = new Vector3(Random.Range(1f, 2f), 1f, 1f);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Platform"))
{
playerRigidbody.velocity = Vector2.up * jumpForce;
Destroy(collision.gameObject);
}
else if (collision.CompareTag("GameOver"))
{
GameOver();
}
}
private void GameOver()
{
isGameOver = true;
gameOverPanel.SetActive(true);
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
```
请注意:这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。
阅读全文