源码学习网

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

小游戏的开始界面:
感兴趣的同学可以点击下载资源,和简易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脚本:
版权声明:快乐源于分享,转载请附链接,,, https://blog.csdn.net/Czhenya/article/details/77929353
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脚本:
[csharp] view plain copy 
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();  
        }  
    }  
}  

 

posted @ 2018-03-29 22:34  马丁啉  阅读(933)  评论(0)    收藏  举报