在unity中当按下空格键时,让方块在2秒的时间完成颜色由深到浅渐变 当按下WSAD键,方块分别向上下左右移动。 程序一开始在5秒内产生一面10*10的砖墙,颜色随机 提示:利用协程完成。
时间: 2024-03-24 19:41:22 浏览: 93
在Unity中捕捉Android的常用按钮返回事件
好的,以下是实现你要求的功能的代码示例:
```csharp
using System.Collections;
using UnityEngine;
public class CubeController : MonoBehaviour
{
public float moveSpeed = 2f; // 方块移动速度
public float colorChangeTime = 2f; // 颜色渐变时间
public GameObject brickWallPrefab; // 砖墙预制件
public float wallSpawnTime = 5f; // 砖墙产生时间
private Renderer cubeRenderer; // 方块渲染器
private Color originalColor; // 方块原始颜色
private Color targetColor; // 目标颜色
private bool isColorChanging = false; // 是否正在进行颜色渐变
// Start is called before the first frame update
void Start()
{
cubeRenderer = GetComponent<Renderer>();
originalColor = cubeRenderer.material.color;
SpawnBrickWall();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(ChangeColor());
}
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(h, 0f, v);
transform.Translate(movement * moveSpeed * Time.deltaTime);
}
IEnumerator ChangeColor()
{
if (isColorChanging)
{
yield break;
}
isColorChanging = true;
float timeElapsed = 0f;
targetColor = new Color(Random.value, Random.value, Random.value);
while (timeElapsed < colorChangeTime)
{
cubeRenderer.material.color = Color.Lerp(originalColor, targetColor, timeElapsed / colorChangeTime);
timeElapsed += Time.deltaTime;
yield return null;
}
cubeRenderer.material.color = targetColor;
originalColor = targetColor;
isColorChanging = false;
}
void SpawnBrickWall()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Vector3 position = new Vector3(i - 4.5f, 0.5f, j - 4.5f);
GameObject brickWall = Instantiate(brickWallPrefab, position, Quaternion.identity);
brickWall.GetComponent<Renderer>().material.color = new Color(Random.value, Random.value, Random.value);
}
}
StartCoroutine(StartMoving());
}
IEnumerator StartMoving()
{
yield return new WaitForSeconds(wallSpawnTime);
while (true)
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(h, 0f, v);
transform.Translate(movement * moveSpeed * Time.deltaTime);
yield return null;
}
}
}
```
在上面的代码中,我们使用协程来实现颜色渐变和等待砖墙的产生。同时,我们还使用了GetAxis来获取WSAD键的输入,来控制方块的移动。
希望这个回答能够对你有所帮助!
阅读全文