Away3D simple collision demo
Demonstrates simple object collision in Away3D without a physics engine.
Use the keyboard left and right arrows to move the cube.
♥0 |
Line 89 |
Modified 2013-08-14 01:39:35 |
MIT License
archived:2017-03-09 19:36:25
ActionScript3 source code
/**
* Copyright tarkin000 ( http://wonderfl.net/user/tarkin000 )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/nFOp
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.geom.Vector3D;
import flash.ui.Keyboard;
import away3d.containers.*;
import away3d.entities.*;
import away3d.lights.*;
import away3d.materials.*;
import away3d.materials.lightpickers.StaticLightPicker;
import away3d.primitives.*;
public class A3DCollision extends Sprite {
private var view:View3D;
private var light:DirectionalLight;
private var lightPicker:StaticLightPicker;
private var floorMaterial:ColorMaterial;
private var floor:Mesh;
private var cubeMaterial:ColorMaterial;
private var cube:Mesh;
private var sphereMaterial:ColorMaterial;
private var sphere:Mesh;
private var collideMaterial:ColorMaterial;
private var key:uint = NaN;
public function A3DCollision() {
if (stage) init();
else (addEventListener(Event.ADDED_TO_STAGE, init));
}
private function init(e:Event = null):void {
light = new DirectionalLight(-1,0,0);
light.x = 500;
light.y = 500;
light.z = -500;
light.ambient = .75;
light.diffuse = .75;
lightPicker = new StaticLightPicker([light]);
view = new View3D();
view.camera.y = 100;
view.camera.z = -500;
view.camera.lookAt(new Vector3D());
view.scene.addChild(light);
this.addChild(view);
floorMaterial = new ColorMaterial();
floorMaterial.lightPicker = lightPicker;
floor = new Mesh(new PlaneGeometry(1000,1000),floorMaterial);
floor.y = -51;
view.scene.addChild(floor);
cubeMaterial = new ColorMaterial(0x3333FF);
cubeMaterial.lightPicker = lightPicker;
cube = new Mesh(new CubeGeometry(), cubeMaterial);
cube.x = -100;
cube.showBounds = true;
view.scene.addChild(cube);
sphereMaterial = new ColorMaterial(0xFF3333);
sphereMaterial.lightPicker = lightPicker;
sphere = new Mesh(new SphereGeometry(), sphereMaterial);
sphere.x = 100;
sphere.showBounds = true;
view.scene.addChild(sphere);
collideMaterial = new ColorMaterial(0x33FF33);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
private function onEnterFrame(e:Event) {
if (key) {
switch (key) {
case Keyboard.LEFT:
cube.x -= 1;
break;
case Keyboard.RIGHT:
cube.x += 1;
break;
}
}
if (cube.worldBounds.overlaps(sphere.worldBounds)) cube.material = collideMaterial;
else cube.material = cubeMaterial;
view.render();
}
private function onKeyDown(e:KeyboardEvent) {
key = e.keyCode;
e.stopPropagation();
}
private function onKeyUp(e:KeyboardEvent) {
key = NaN;
e.stopPropagation();
}
}
}