unity过马路游戏的代码
时间: 2023-07-09 14:33:21 浏览: 51
以下是一个简单的Unity过马路游戏的代码示例,其中玩家需要控制一个角色穿过繁忙的街道,避免被车撞:
```C#
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public float leftBound = -5f;
public float rightBound = 5f;
public Transform startingPosition;
public Rigidbody2D rb;
private bool isAlive = true;
void Start()
{
// Set starting position
transform.position = startingPosition.position;
}
void Update()
{
if (isAlive)
{
// Horizontal movement
float moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// Jumping
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpForce;
}
// Check if player is out of bounds
if (transform.position.x < leftBound || transform.position.x > rightBound)
{
Die();
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Car")
{
Die();
}
}
void Die()
{
isAlive = false;
Debug.Log("Game over!");
// Show game over screen, restart level, etc.
}
}
```
在这个示例中,玩家被控制着在水平方向移动,并且可以跳跃以避免被车撞。如果玩家越界或与车碰撞,游戏将结束。您可以根据需要自定义和扩展这个示例来创建您自己的过马路游戏。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)