Unity3D 5.0简单的射线检测实现跳跃功能
这里是一个简单的跳跃,5.0和其他版本貌似不一样,并且,再起跳功能做的不完全。
不过一个基本的思路在这里。
1.首先,射线检测,这里是利用一个空对象,放到主角对象的下面
2.然后调节射线的位置,在主角对象的下面一点(这点很重要,差不多放在脚下,这样才能和地面接触,不然就永远也和地面接触不了)
LineCast 两点之间产生射线,去和某个碰撞器发生碰撞,触发了碰撞器,返回一个真
先定义要碰撞的碰撞器的层
然后,在绑定主角的脚本文件上开始写脚本:
using UnityEngine; using System.Collections; public class move : MonoBehaviour { // Use this for initialization private bool grounded = false; private Transform groundcheck; private bool jump = false; //角色的跳起 private Rigidbody2D hero; public float jumpy = 360f; public AudioClip jumpclips; //跳跃音频 void Start () { groundcheck = transform.Find ("groundcheck"); //hero = transform.Find ("pk_0"); } // Update is called once per frame void Update () { if(Input.GetKey(KeyCode.W)){ gameObject.transform.Translate(Vector3.up*5*Time.deltaTime); } if(Input.GetKey(KeyCode.S)){ gameObject.transform.Translate(Vector3.down*5*Time.deltaTime); } if(Input.GetKey(KeyCode.A)){ gameObject.transform.Translate(Vector3.left*5*Time.deltaTime); } if(Input.GetKey(KeyCode.D)){ gameObject.transform.Translate(Vector3.right*5*Time.deltaTime); } //与地面接触为真,太能够进行跳跃 grounded = Physics2D.Linecast (transform.position, groundcheck.transform.position,1 << LayerMask.NameToLayer("Ground")); if(grounded && Input.GetKeyDown(KeyCode.J)){ jump = true; //设置角色的起跳功能 if(jump == true){ AudioSource.PlayClipAtPoint(jumpclips,gameObject.transform.position); gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f,jumpy)); //hero.AddForce(new Vector2(0f,1000f)); jump = false; grounded = false; } } Debug.DrawLine (transform.position, groundcheck.transform.position,Color.red,1f); } }