Multitouch Pong
forked from Chapter 23 Example 4 (diff: 74)
ActionScript3 source code
/**
* Copyright makc3d ( http://wonderfl.net/user/makc3d )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/vFxO
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
[SWF(width=465,height=465)]
public class Pong extends Sprite {
public var p1:Paddle;
public var p2:Paddle;
public var ball:Ball;
public function Pong () {
try {
var test:Class = Multitouch;
if (Multitouch.supportsTouchEvents) {
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
if (Multitouch.maxTouchPoints > 1) {
addChild (ball = new Ball);
addChild (p1 = new Paddle (30));
addChild (p2 = new Paddle (465 - 30));
stage.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin);
stage.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
} else {
trace ("Sorry, no pong for you :(");
}
} else {
trace("Sorry, your device doesn't support touch-level events");
}
} catch (error:ReferenceError) {
trace("Sorry, but multitouch is not supported in this runtime.");
}
}
protected function onTouchBegin(event:TouchEvent):void {
var p:Paddle = event.target as Paddle;
if (!p) return;
p.startTouchDrag(event.touchPointID, false, p.bounds);
}
protected function onTouchEnd(event:TouchEvent):void {
var p:Paddle = event.target as Paddle;
if (!p) return;
p.stopTouchDrag(event.touchPointID);
}
protected function onEnterFrame (e:Event):void {
if ((ball.y > 465 - 20) || (ball.y < 20)) ball.dy *= -1;
if (ball.x < p1.x + 20) {
if (ball.x < p1.x + 20 - 2) {
// point of no return
if (ball.x < -10) {
// score
ball.dx *= -1; ball.x = int (465 / 2);
}
} else {
// check collision
if (Math.abs (p1.y - ball.y) < 60) {
ball.dx *= -1;
}
}
}
if (ball.x > p2.x - 20) {
if (ball.x > p2.x - 20 + 2) {
// point of no return
if (ball.x > 465 +10) {
// score
ball.dx *= -1; ball.x = int (465 / 2);
}
} else {
// check collision
if (Math.abs (p2.y - ball.y) < 60) {
ball.dx *= -1;
}
}
}
ball.x += ball.dx;
ball.y += ball.dy;
}
}
}
import flash.display.Sprite;
import flash.geom.Rectangle;
class Paddle extends Sprite {
public var bounds:Rectangle;
public function Paddle (x0:Number) {
x = x0; y = 465 / 2;
bounds = new Rectangle (x0, 70, 0, 465 - 2 * 70);
graphics.beginFill (0xFF7F00);
graphics.drawRect (-10, -50, 20, 100);
}
}
class Ball extends Sprite {
public var dx:Number = 2;
public var dy:Number = 2;
public function Ball () {
x = y = int (465 / 2);
graphics.beginFill (0xFF7F7F);
graphics.drawRect (-10, -10, 20, 20);
}
}