这里提供的角色移动方式是:
- 每按下一个按键,移动一格
- 角色移动一格与下一格之间有休息时间
using System.Collections; using System.Collections.Generic; using UnityEngine; public class move : MonoBehaviour { public float smoothing=6.0f; public float restTime = 0.3f; public float restTimer = 0.0f; private Vector2 targetPos = new Vector2 (1,1); private Rigidbody2D rb; private BoxCollider2D cd; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D> (); cd = GetComponent<BoxCollider2D> (); } // Update is called once per frame void Update () { } void FixedUpdate () { rb.MovePosition (Vector2.Lerp(transform.position,targetPos,smoothing*Time.deltaTime)); restTimer += Time.deltaTime; if (restTimer < restTime) return; float h = Input.GetAxisRaw ("H"); float v = Input.GetAxisRaw ("V"); if(h!=0){ v = 0; } if(h!=0||v!=0){ cd.enabled = false; RaycastHit2D hit= Physics2D.Linecast (targetPos,targetPos+new Vector2(h,v)); cd.enabled = true; if (hit.transform == null) { targetPos += new Vector2 (h, v); } else { switch(hit.collider.tag){ case "outsidewall": break; case "insidewall": hit.collider.SendMessage ("TakeDamage"); break; case "food": GameManager.getGM.addHP (10); targetPos += new Vector2 (h, v); Destroy (hit.transform.gameObject); break; } } restTimer = 0; } } }
射线检测 放到fixedupdate 应该好点
@LegendFox:嗯嗯,多谢大佬提醒