// prg6-2 角色左右移動加速&跳躍 using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { // Start is called before the first frame update Rigidbody2D rigid2D; float jumpForce = 680.0f; float walkForce = 30.0f; float maxWalkSpeed = 2.0f; void Start() { this.rigid2D = GetComponent(); } // Update is called once per frame void Update() { // Jump if(Input.GetKeyDown(KeyCode.Space)) { this.rigid2D.AddForce(transform.up * this.jumpForce); } // 左右移動 int key = 0; if(Input.GetKey(KeyCode.RightArrow)) key = 1; if(Input.GetKey(KeyCode.LeftArrow)) key = -1; //遊戲角色速度 float speedx = Mathf.Abs(this.rigid2D.velocity.x); // 速度限制 if(speedx < this.maxWalkSpeed) { this.rigid2D.AddForce(transform.right * key * this.walkForce); } } }