加宽挡板
Coddy Unity 游戏:打砖块 课程的第 16 课,共 19 课。
定时效果就是一个协程:改变,等待,再改回来。如果第一个效果还在运行时再次接住道具,就必须重新开始计时,因此要保存 StartCoroutine 返回的 Coroutine,并在启动新协程前停止它。否则第一个协程会提前结束,撤销第二个效果。速度提升效果:
if (boost != null) StopCoroutine(boost);
boost = StartCoroutine(BoostFor(3f));
IEnumerator BoostFor(float seconds)
{
speed = normalSpeed * 2f;
yield return new WaitForSeconds(seconds);
speed = normalSpeed;
boost = null;
}它根据只保存一次的 normalSpeed 设置速度,而不是将当前速度翻倍:连续获得两次速度提升,速度就会变成 4 倍。挡板的边界限制每一步都会读取它的宽度,因此即使挡板变宽,也仍会停在墙边。
挑战
困难宽度道具会让挡板变宽,持续 8 秒。
- 在
Paddle中,添加public float wideFactor = 1.6f;和public float wideSeconds = 8f;,并在 Awake 中保存正常的 x 缩放值。 - Widen() 会停止正在运行的协程(如果有),然后启动一个协程:将 x 缩放值设为正常值乘以
wideFactor,等待wideSeconds,再恢复正常值。 - 协程需要
using System.Collections;。
按下 Play,接住一个绿色道具:挡板会变宽,然后恢复原状。然后点击 Check。
亲手试试
using UnityEngine;
using UnityEngine.InputSystem;
public class Paddle : MonoBehaviour
{
public float speed = 14f;
public float wallX = 8f; // 两侧墙壁的内侧分别位于 -wallX 和 wallX
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float input = 0f;
if (Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed) input -= 1f;
if (Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed) input += 1f;
Vector3 target = rb.position + Vector3.right * input * speed * Time.fixedDeltaTime;
float halfWidth = transform.localScale.x / 2f;
target.x = Mathf.Clamp(target.x, -wallX + halfWidth, wallX - halfWidth);
rb.MovePosition(target);
}
public void Widen()
{
Debug.Log("Wide paddle");
}
}
Unity 游戏:打砖块中的所有课
自己练习: Unity 在线编辑器