Unity3D --//通過射線判斷角色是否在地面
阿新 • • 發佈:2019-01-03
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerContro : MonoBehaviour { public float speed; public Animator myAnimator; public SpriteRenderer spriteRenderer; // Use this for initialization private bool isGround = false; private Rigidbody2D myRigidbody2D; void Start () { myAnimator = GetComponent<Animator>(); myRigidbody2D = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { float x = Input.GetAxis("Horizontal"); //旋轉邏輯 if (x >0) { spriteRenderer.flipX = false; } else if(x < 0) { spriteRenderer.flipX = true; } //角色是否在地面 Debug.DrawRay(transform.position, Vector2.down * 0.11f, Color.red); RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 0.15f, 1 << 8); if (hit.collider != null) { isGround = true; } else { isGround = false; } //角色狀態 if (!isGround)//角色沒有與地面接觸 { // myAnimator.SetInteger("player_state", 2); myAnimator.Play("jump"); } else //校色與地面接觸 { if (x == 0) { // myAnimator.SetInteger("player_state", 0); myAnimator.Play("idle"); } else { // myAnimator.SetInteger("player_state", 1); myAnimator.Play("run"); } } //角色行為控制 transform.Translate(Vector3.right*x*Time.deltaTime*speed); // myRigidbody2D.velocity = Vector2.right * x * speed; // myRigidbody2D.MovePosition(Vector2.right*x*Time.deltaTime*speed); // myRigidbody2D.MovePosition(myRigidbody2D.position + Vector2.right * speed * Time.deltaTime * x); // Vector2 vector2 = new Vector2(1, 0.0f) * speed * x; // myRigidbody2D.velocity = vector2; if (Input.GetKeyDown("space")) { if (isGround) { myRigidbody2D.AddForce(Vector2.up * 180); } } } }