撰写了文章 更新于 2017-07-11 19:03:54
Unity2D-PingPong开发实例二
时间过得真的是挺快的,上周忙于公司搬迁事宜,好不容易凑了个下雨天继续归纳后续的简单步骤
Part1:https://cowlevel.net/article/1895976
Player位置生成
拖拽Player生成Prefabs,并复制生成两块挡板分居屏幕左右。
编辑GameManager Scripts,负责控制Player的生成位置
public Transform player1,player2;
void PlayerReset(){
Vector3 player1Position = Camera.main.ScreenToWorldPoint(new Vector3(100,Screen.height/2,0));
player1Position.z=0;
player1.position=player1Position;
Vector3 player2Position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width - 100, Screen.height / 2, 0));
player2Position.z = 0;
player2.position = player2Position;
}
注意拖拽对应刚体至player1及player2
添加弹性物件小球
从Sprites中添加小球(亦可自行生成)
添加CircleCollider2D
添加RigidBody2D
新建Material→Physical Material 2D, Friction 0, Bounciness 1
Collider2D中调用该Material
在游戏中通过调节Gravity测试小球的弹性属性是否被正确应用上
添加Scripts BallController
///
/// 控制小球初始力随机方向及移动
///
void GoBall(){
int number = Random.Range(0,2);
if(number==1){
GetComponent().AddForce(new Vector2(100,0));
else{
GetComponent().AddForce(new Vector2(-100, 0));
}
}
}
void Start(){
GoBall();
}
///
/// 小球碰撞检测
///
void OnCollisionEnter2D(Collision2D col)
if(col.collider.tag=="Player"){//注意添加tag标签
Vector2 velocity = GetComponent().velocity;
velocity.y = col.rigidbody.velocity.y/2f + velocity.y/2f;
GetComponent().velocity = velocity;
}
a
MonoBehaviour.OnCollisionEnter2D(Collision2D) 当进入2D碰撞
Sent when an incoming collider makes contact with this object's collider (2D physics only).
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Enemy")
coll.gameObject.SendMessage("ApplyDamage", 10);
}
}Collision2D.rigidbody
The incoming Rigidbody2D involved in the collision.
控制小球速度.x的维持
经测试观察,小球的速度在某些时段会触发bug导致移动速度变慢,可通过以下代码输出观察
Debug.log(GetComponent().velocity)
故编辑BallController Scripts,新建方法BallVelocityReset,并在Update中调用
void BallVelocityReset(){
Vector2 velocity = GetComponent().velocity;
if(velocity.x<9 && vlocity.x>-9 && velocity.x!=0){
if(velocity.x>0){
velocity.x = 10;
}else{
velocity.x = -10;
}
GetComponent().velocity = velocity;
}
}