2D赛车 - Whell joint 2D组件的使用

2020-11-11 14:54发布

git:https://github.com/Czhenya/SmallDemo

码云:https://gitee.com/Czhenya/2DSaiChe

小游戏的开始界面:


感兴趣的同学可以点击下载资源,和简易unitypackage,,,链接:http://pan.baidu.com/s/1pLTyf9p 密码:v392

根据车轮的转动,使小车运动,,,


使用2D Sprite创建出入下图所示关系,并附上图片调整位置:

为小车,和车轮增加如下的属性面板

CarMove脚本在后面,,没有声音面板,需要就加AudioSound组件,就好了,大家注意面板上的属性赋值就可以了,

注意:whell Join 2D 属性面板的Connected Anchor 属性一定调整到车轮的中心点位置,,这里的物理材质我使用的摩擦力大小时0.5,,,车的rigidbody赋值在车轮的Whell Joint 属性上,,勾选上Use Motor,调整各自的碰撞体;


CarMove脚本:

public class CarMove : MonoBehaviour {

 

    public float speed = 10f;    //初速度

 

    public WheelJoint2D leftWhell;  //车轮

    public WheelJoint2D rightWhell;

 

    public float phSpeed = 5.0f;  //平衡调整速度

 

    public AudioSource carSound;  //获取组件以播放声音

    public AudioClip runClip;   //开车时的音频剪辑

    public AudioClip waitClip;  

 

    private Transform myTrans;  //自己的Transform

 

    //给车轮加动力的

    private JointMotor2D jmL,jmR;

 

void Start () {

        //获取速度

        jmL = leftWhell.motor;

        jmR = rightWhell.motor;

 

        myTrans = this.transform;

 

    }

// Update is called once per frame

void Update () {

        Move();

    }

 

    private void Move()

    {

        //获取输入

        float ax = Input.GetAxis("Horizontal");

        float ay = Input.GetAxis("Vertical");

 

        //当前速度

        jmL.motorSpeed = ax * speed;

        jmR.motorSpeed = ax * speed;

        //赋值

        leftWhell.motor = jmL;

        rightWhell.motor = jmR;

 

        if(ay != 0)

        {

            //左右平衡赛车的角度

            myTrans.Rotate(myTrans.forward, ay * phSpeed);

        }

 

      if ( ax != 0 ) //有移动变化量就不播放runClip

        {

            carSound.clip = runClip;

 

            if(!carSound.isPlaying){

                carSound.Play();

            }

 

        }else  //停下就不播放声音

        {

            carSound.Stop();

        }

    }

}




作者:Czhenya

链接:https://czhenya.blog.csdn.net/article/details/77929353

来源:CSDN
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。