撰写了文章 发布于 2017-07-13 23:22:40
Unity2D-PingPong开发实例四 [完]
Part1:https://cowlevel.net/article/1895976
Part2:https://cowlevel.net/article/1897397
Part3:https://cowlevel.net/article/1897671
添加音效系統
合适恰当的音乐插入会有画龙点睛之感。本游戏主要添加的音乐有三段,分别为小球碰触Player的音效、小球碰触墙壁产生的音效、游戏背景乐
Player → AudioSource,添加碰撞音效,勾选 Play on Awake。为使每次碰撞产生的声音不至于过于单调,通过脚本随机Pitch,编辑PlayerController脚本,代码如下
private AudioSource audio;
void Start(){
audio = GetComponent();
}
void OnCollisionEnter2D(Collison2D col){
audio.pitch = Random.Range(0.8f,1.2f);
audio.Play();
}
继续添加碰触墙壁后的声音效果
任选rightWall或者leftWall组件,并挂载上AudioSource及对应脚本
编辑wallAudio脚本
private AudioSource audio;
void Start(){
audio = GetComponent<AudioSource>();
}
void OnCollisionEnter2D(){
audio.Play{};
}
最后添加BGM。直接挂载在GameManger上,并选中PlayOnAwake及Loop即可。
添加Reset按钮并实现归零重置功能
Canvas Add Button,Text→Reset
Button Inspector中,有几个选项分别负责控制按钮的外观显示功能,分别为:
Image(Script)→SourceImage:Button基础图像
Button(Script)→HeighLighted/Pressed Sprite ,分别指代光标移动及按下时的图案变化
编辑GameManager脚本,新增Reset方法,并在Button中实现调用

(注意需先在脚本中创建好该方法,并在Button属性中添加 RuntimeOnly,调用该方法)
public void Reset(){
score1=0;
score2=0;
score1Text.text = score1.ToString();
score2Text.text = score2.ToString();
PlayerReset();
GameObject.Find("Ball").SendMessage("BallReset");//该方法在BallController脚本中做补充。功能是使小球回到原位
GameObject.Find("Ball").SendMessage("BallVelocityReset");
}编辑BallController脚本,并新增BallReset方法
public void BallReset(){
transform.position = Vector3.zero;
GoBall();//小球初始随机左右施力开始运动
}GameObject.SendMessage
void SendMessage(string methodName, object value = null, SendMessageOptions options = SendMessageOptions.RequireReceiver);
Parameters
methodName The name of the method to call. value An optional parameter value to pass to the called method. options Should an error be raised if the method doesn't exist on the target object? Description
Calls the method named /methodName/ on every MonoBehaviour in this game object.
The receiving method can choose to ignore the argument by having zero parameters. If options is set to SendMessageOptions.RequireReceiver an error is printed if the message is not picked up by any component.
Note that messages will not be sent to inactive objects (ie, those that have been deactivated in the editor or with the SetActive function).
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void ApplyDamage(float damage) {
print(damage);
}
void Example() {
gameObject.SendMessage("ApplyDamage", 5.0F);
}
}
源代码地址
链接: https://pan.baidu.com/s/1gfKhvsZ 密码: fhnz
欢迎有任何问题前来交流,直接留言即可。
睡觉Zzz
Yeah!