Shoot multiple bullets in a 360 degree spread? - actionscript-3

I want this sort of effect:
http://i.imgur.com/xGi46.png
So wherever I click, it makes a bomb type effecting using the bullets.
Here's my code so far. Right now it only creates bullets in the direction of the mouse.
Sorry if the code is messy.
shotDex = new Timer(timerDelay2);
shotDex.addEventListener(TimerEvent.TIMER, shot);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shootBullet);
stage.addEventListener(MouseEvent.MOUSE_UP, dontShoot);
public var angleRadian = Math.atan2(mouseY + 42.75,mouseX + 331.7);
public var angleDegree = angleRadian * 180 / Math.PI;
public var speed1:int = 10;
public var shotDex:Timer;
public var timerDelay2:int = (250);
public function shot(tEvt:TimerEvent)
{
var _bullet2:bullet2 = new bullet2;
_bullet2.x = 300;
_bullet2.y = 300;
_bullet2.angleRadian = Math.atan2(mouseY + 42.75,mouseX + 331.7);
_bullet2.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
stage.addChild(_bullet2);
}
public function shootBullet(evt:MouseEvent)
{
var _bullet2:bullet2 = new bullet2;
_bullet2.x = 300;
_bullet2.y = 300;
_bullet2.angleRadian = Math.atan2(mouseY + 42.75,mouseX + 331.7);
stage.addChild(_bullet2);
_bullet2.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
shotDex.start();
}
public function bulletEnterFrame(evt:Event)
{
var _bullet2 = evt.currentTarget;
_bullet2.x += Math.cos(_bullet2.angleRadian) * speed1;
_bullet2.y += Math.sin(_bullet2.angleRadian) * speed1;
_bullet2.rotation = _bullet2.angleRadian * 180 / Math.PI;
if (_bullet2.x < 0 || _bullet2.x > 600 || _bullet2.y < 0 || _bullet2.y > 600)
{
stage.removeChild(_bullet2);
_bullet2.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
}
public function dontShoot(evt:MouseEvent)
{
shotDex.stop();
}

You need to provide a different angle for each bullet, with values evenly spaced between 0 radians and 2 * Math.PI radians:
public function shootBulletCircle(evt:MouseEvent) {
var shots:Number = 12; // Number of shots in the circle
for (var i=0; i<shots; i++) {
var _bullet2:bullet2 = new bullet2;
_bullet2.x = 300;
_bullet2.y = 300;
_bullet2.angleRadian = (i/shots)*(2*Math.PI);
stage.addChild(_bullet2);
_bullet2.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
}
As an optional side note: DisplayObject (which is probably a superclass of your Bullets) has a rotation property, which is used automatically when drawing, but it expects that value in degrees. You could try calculating degrees, storing that as the bullet's rotation value, and get rid of angleRadian entirely.

Related

MouseEvent Not Happening On Click AS3

This looks all fine to me, but I have a simple star shape on the screen and when that star shape has been clicked it should remove the image from the screen. Can't see why its not working hoping one of you can, would be much appreciated
public class TouchRemove extends Sprite
{
private var _color:uint;
private var _radius:int;
private var star:Sprite;
public function mouseClick(event:MouseEvent): void {
star.visible = false;
}
public function TouchRemove(c:uint = 0xffff00, r:int = 100)
{
_color = c;
_radius = r;
star = new Sprite();
createStar();
addChild(star);
star.x = 250;
star.addEventListener(MouseEvent.CLICK, mouseClick);
}
private function createStar():void
{
star.graphics.lineStyle(9,_color);
star.graphics.moveTo(_radius, 0);
var angleIncrement = Math.PI / 5;
var ninety:Number = Math.PI * 3;
for (var i:int = 0; i <= 10; i++)
{
var radius:Number = (i % 2 > 0 ? _radius : _radius * .5);
var px:Number = Math.cos(ninety + angleIncrement * i) * radius;
var py:Number = Math.sin(ninety + angleIncrement * i) * radius;
if (i == 0) star.graphics.moveTo(px, py);
star.graphics.lineTo(px, py);
}
}
}
}
Your code looks correct.
Try this:
- Add listener to the parent
- Add star manually and add listener at it through the code
This will help locate the error.

Action Script 3. Spawn objects in different time

I'm creating game where falling 4 different objects from the sky and need to destroy them by clicking mouse button. My problem is that all 4 objects spawns at the same time. I need to make that randomly spawned all 4, but not in the same time and after player have 200 points I need to make that spawned and falled more objects. (I have working counter which counting points).
And one more thing if you know how to make that objects not spawned on one other.
I mean:
Bad spawn.
Here is my constant vars:
public static const GRAVITY:Number = 3;
public static const HIT_TOLERANCE:Number = 50;
//Powerup
public static const APPLE_END_Y:Number = 640;
public static const APPLE_SPAWN_CHANCE:Number = 0.02; //per frame per second
public static const APPLE_START_Y:Number = 110;
public static const APPLE_SPAWN_START_X:Number = 50;
public static const APPLE_SPAWN_END_X:Number = 500;
//Scoring
public static const PLAYER_START_SCORE:Number = 0;
public static const SCORE_PER_APPLE:Number = 10;
Here is part of my code:
public function startGame()
{
speed = C.PLAYER_SPEED;
gravity = C.GRAVITY;
score = C.PLAYER_START_SCORE;
randomChance = C.APPLE_SPAWN_CHANCE;
tol = C.HIT_TOLERANCE;
apples = new Array();
mcGameStage.addEventListener(Event.ENTER_FRAME,update);
}
private function update(evt:Event)
{
//Spawn new apples
if (Math.random() < randomChance)
{
//spawn x coordinates
var newPirmas = new Pirmas();
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newAntras = new Antras();
newAntras.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newTrecias = new Trecias();
newTrecias.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newApple = new Apple();
newApple.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
//spawn y coordinates
newPirmas.y = C.APPLE_START_Y;
newAntras.y = C.APPLE_START_Y;
newTrecias.y = C.APPLE_START_Y;
newApple.y = C.APPLE_START_Y;
apples.push(newPirmas);
apples.push(newAntras);
apples.push(newTrecias);
apples.push(newApple);
newPirmas.addEventListener(MouseEvent.CLICK, onClick);
newAntras.addEventListener(MouseEvent.CLICK, onClick);
newTrecias.addEventListener(MouseEvent.CLICK, onClick);
newApple.addEventListener(MouseEvent.CLICK, onClick);
mcGameStage.addChildAt(newPirmas,0);
mcGameStage.addChildAt(newAntras,0);
mcGameStage.addChildAt(newTrecias,0);
mcGameStage.addChildAt(newApple,0);
}
//Move Apples
for (var i = apples.length-1; i >= 0; i--)
{
apples[i].y += gravity;
if (apples[i].y > C.APPLE_END_Y)
{
mcGameStage.removeChild(apples[i]);
apples.splice(i,1);
m_iLives--;
if (!m_iLives)
{
trace("Game Over");
// newApple.removeEventListener(MouseEvent.CLICK, onClick);
break;
}
}
}
txtScore.text = String(score);
}
function onClick(evt:MouseEvent):void{
var apples = evt.target;
apples.visible = false;
apples = tol;
score += C.SCORE_PER_APPLE;
}
}
public function startGame()
{
speed = C.PLAYER_SPEED;
gravity = C.GRAVITY;
score = C.PLAYER_START_SCORE;
randomChance = C.APPLE_SPAWN_CHANCE;
tol = C.HIT_TOLERANCE;
apples = [];
itemsToSpawn = [];
mcGameStage.addEventListener(Event.ENTER_FRAME,update);
nextSpawn:Number = 0;
}
private function update(evt:Event)
{
//Spawn new apples
if (Math.random() < randomChance)
{
//spawn x coordinates
var newPirmas = new Pirmas();
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newAntras = new Antras();
newAntras.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newTrecias = new Trecias();
newTrecias.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newApple = new Apple();
newApple.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
//spawn y coordinates
newPirmas.y = C.APPLE_START_Y;
newAntras.y = C.APPLE_START_Y;
newTrecias.y = C.APPLE_START_Y;
newApple.y = C.APPLE_START_Y;
newPirmas.addEventListener(MouseEvent.CLICK, onClick);
newAntras.addEventListener(MouseEvent.CLICK, onClick);
newTrecias.addEventListener(MouseEvent.CLICK, onClick);
newApple.addEventListener(MouseEvent.CLICK, onClick);
//add items to itemsToAdd
itemsToAdd.push(newPirmas, newAntras, newTrecias, newApple);
}
//Move Apples
for (var i = apples.length-1; i >= 0; i--)
{
apples[i].y += gravity;
if (apples[i].y > C.APPLE_END_Y)
{
mcGameStage.removeChild(apples[i]);
apples.splice(i,1);
m_iLives--;
if (!m_iLives)
{
trace("Game Over");
// newApple.removeEventListener(MouseEvent.CLICK, onClick);
break;
}
}
}
txtScore.text = String(score);
if( itemsToSpawn.length > 0 && getTimeout() > nextSpawn )
{
var item:DisplayObject = itemsToAdd.shift();
apples.push(item);
mcGameStage.addChild(item);
nextSpawn = getTimeout() + Math.random() * 4000;
}
}
function onClick(event:MouseEvent):void
{
var apples = event.currentTarget;
apples.visible = false;
apples = tol;
score += C.SCORE_PER_APPLE;
if(score % 100 == 0)
{
gravity += 10;
}
}
In your update code, you're checking a single time for a random value to be less than randomChance, and when it is, you spawn 4 apples.
If you want them to spawn at different times, you would call them one at a time. I would make a function to create a randomly placed apple, and call that whenever your if statement is satisfied.
Eg:
private function update(evt:Event){
if(Math.random() < randomValue){
createApple();
}
Where createApple() would create a new apple, position it, add it to the array, and add it to the stage.
If you're trying to create a different apple each time, you can put the different types in an array and iterate through it as you create new apples.
EG.
private function createApple(){
...
var newApple = appleToSpawn[currentApple]
...
}
Where appleToSpawn is an array of apple objects, and currentApple is an index of which apple you're currently on.
Alternatively, you could do a series of comparisons to a random number, and spawn a different apple depending on which condition is satisfied.
As for making sure they don't overlap, you can keep a history of their spawn points, and change how you get their random X value. Just iterate through the array of previous X values, and make sure the new one isn't within (oldX + (width/2)).
Now for spawning more than 4 as you get more points, just change your randomChance to a bigger number as you go. If it's a bigger number, you'll satisfy your conditional statement more often, therefor spawning more apples.

Action Script 3. How to remember last object x coordinates

I'm creating a flash game where objects are falling from the sky and the player needs to destroy them by clicking on them. But I have a problem, sometimes they spawning one on top of each other.
Here is an example what I mean:
Objects should be spawned near other, but not one on other.
Here is my constant vars:
public static const GRAVITY:Number = 3;
public static const HIT_TOLERANCE:Number = 50;
//Powerup
public static const APPLE_END_Y:Number = 640;
public static const APPLE_SPAWN_CHANCE:Number = 0.02; //per frame per second
public static const APPLE_START_Y:Number = 110;
public static const APPLE_SPAWN_START_X:Number = 50;
public static const APPLE_SPAWN_END_X:Number = 500;
//Scoring
public static const PLAYER_START_SCORE:Number = 0;
public static const SCORE_PER_APPLE:Number = 10;
Here is part of code where objects spawning:
private function update(evt:Event)
{
//Spawn new apples
if (Math.random() < randomChance)
{
//spawn x coordinates
var newPirmas = new Pirmas();
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newAntras = new Antras();
newAntras.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newTrecias = new Trecias();
newTrecias.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
var newApple = new Apple();
newApple.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
//spawn y coordinates
newPirmas.y = C.APPLE_START_Y;
newAntras.y = C.APPLE_START_Y;
newTrecias.y = C.APPLE_START_Y;
newApple.y = C.APPLE_START_Y;
newPirmas.addEventListener(MouseEvent.CLICK, onClick);
newAntras.addEventListener(MouseEvent.CLICK, onClick);
newTrecias.addEventListener(MouseEvent.CLICK, onClick);
newApple.addEventListener(MouseEvent.CLICK, onClick);
itemsToSpawn.push(newPirmas, newAntras, newTrecias, newApple);
}
}
As someone said: As for making sure they don't overlap, you can keep a history of their spawn points, and change how you get their random X value. Just iterate through the array of previous X values, and make sure the new one isn't within (oldX + (width/2)).
But I can't make It successfully, could you help me with keeping history of their spawn points? Thank you very much.
var t:Array = [];
t[0] = [APPLE_SPAWN_START_X, APPLE_SPAWN_END_X + APPLE_WIDTH/2];
t will keep the available intervals the you can generate new apple.
In the start time, there is no apple, and the t has only one interval, the starX of the interval is APPLE_SPAWN_START_X, the endX of the interval is APPLE_SPAWN_END_X + APP_WIDTH/2.
where you want to generate a new apple, you would find a availble interval in t, if we find the interval as mInterval(the interval could put in the apple, means endX - starX >= APPLE_WIDTH), then we could generate your new apple.
We just need to change the lines in you update function like
newPirmas.x = Math.random() * C.APPLE_SPAWN_END_X + C.APPLE_SPAWN_START_X;
Instead
newPirmas.x = mInterval[0] + Math.random()*APPLE_WIDTH;
When we set newPirmas.x, we have break the mInterval and generate two new interval,
the values are [mInterval[0],newPirmas.x] and []newPirmas.x + APPLE_WIDTH, mInterval[0]],
so we need to delete the mInterval in t and put the two new intervals into t.
/**
*
* #return index of available interval in target array
*/
public static function findAvailInterval(target:Array, appleWidth:int):int {
if (target == null || target.length == 0) {
return -1;
}
var endX:int = 0;
var startX:int = 0;
var length:int = target.length;
for (var i:int = 0; i < length; i++) {
var temp:Array = target[i] as Array;
if (temp == null || temp.length < 2) {
return -1;
}
startX = temp[0];
endX = temp[1];
var intervalWidth:int = endX - startX;//the interval width
if (intervalWidth >= appleWidth) {//find an available one
return i;
}
}
return -1;
}
public static function breakInterval(target:Array, appleWidth:int, index:int):int {
var temp:Array = target[index];
var startX:int = temp[0];
var endX:int = temp[1];
var width:int = endX - startX;
var availableNewXRange:int = width - appleWidth;//the appleā€˜s max x, and the min x is startX
//random a position
var appleX:int = startX + availableNewXRange*Math.random();
var leftInterval:Array = [startX, appleX];//the left interval of apple
var rightInterval:Array = [appleX+appleWidth, endX];//the right interval of apple
//delete temp
target.splice(index, 1);
if (isAvailableInterval(leftInterval, appleWidth)) {
target.push(leftInterval);
}
if (isAvailableInterval(rightInterval, appleWidth)) {
target.push(rightInterval);
} else {
trace("vvv");
}
return appleX;
}
private static function isAvailableInterval(interval:Array, appleWidth:int):Boolean {
if (interval == null || interval.length < 2) {
return false;
}
return (interval[1] - interval[0]) >= appleWidth;
}
Put the three functions into a class A
var target:Array = [[0, 1000]];
var appWidth:int = 80;
for (var i:int = 0; i < 4; i++) {
var index:int = A.findAvailInterval(target, appWidth);
if (index != -1) {
var interval:Array = target[index];
RR.breakInterval(target, appWidth, index);
trace(interval);
}
}

Collision detection and clipping issues in AS3

I've recently started putting together a little physics simulation from scratch, something I've never tried before, and I've run into an issue regarding the interaction between the collision of the objects I have on stage, and what I think is my constant gravity. I'm not sure if 200 lines of code is too large for here, but this is what I have.
package {
import flash.events.*;
import flash.display.*;
import flash.geom.Rectangle;
[SWF (width="1500", height="1000", frameRate="24")]
public class ElasticityV2 extends MovieClip{
/* Gravity is 9.8 m/s2, which for flash, since it's being applied every frame, needs to be
divided out by the frame rate as to not have super fast acceleration. GravMulti is to balance
out gravity's speed, as it seemed a little slow after the framerate division. Resistance is acting
like friction for now, and slows down the objects in the air and on the ground at the same rate.
Elasticity is how bouncy each object is and how the force it recieves is applied*/
public var gravMulti:Number = 5;
public var gravity:Number = gravMulti *(9.8/stage.frameRate);
public var resistance:Number = 0.98;
public var elasticity:Number = 0.8;
public var floor:Number = stage.stageHeight - 100;
public var objectList:Array = new Array();
public var shadowList:Array = new Array();
public var yVelocityList:Array = new Array();
public var xVelocityList:Array = new Array();
public var massList:Array = new Array();
public var frictionList:Array = new Array();
public var lastXList:Array = new Array();
public var lastYList:Array = new Array();
public var elasticityList:Array = new Array();
public var dragList:Array = new Array();
public var spawnNum:int = 20;
public var bounding:Rectangle = new Rectangle(0,0,stage.stageWidth - 100,stage.stageHeight);
public var distantBackground:Background = new Background();
public var starLight:Light = new Light();
public function ElasticityV2() {
addChild(starLight);
starLight.x = stage.stageWidth/2;
starLight.y = -400;
starLight.addEventListener(MouseEvent.MOUSE_DOWN, onLightDrag);
starLight.addEventListener(MouseEvent.MOUSE_UP, onLightDrag);
starLight.addEventListener(MouseEvent.MOUSE_OUT, onLightDrag);
for(var s:int=0;s<spawnNum;s++){
var ballShadow:Shadow = new Shadow();
addChild(ballShadow);
setChildIndex(ballShadow,0);
ballShadow.y = floor - (ballShadow.height/2);
ballShadow.x = 100;
shadowList.push(ballShadow);
var ball:ElasticBall = new ElasticBall();
var dragging:Boolean = false;
addChild(ball);
ball.y = 100;
ball.x = s * 200;
objectList.push(ball);
yVelocityList.push(randomMe(20,-20));
xVelocityList.push(randomMe(40,-40));
massList.push(randomMe(20,5));
frictionList.push(randomMe(0.6,0.01));
objectList[s].width = objectList[s].height = massList[s] * 10;
elasticityList.push(elasticity);
dragList.push(dragging);
ball.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
ball.addEventListener(MouseEvent.MOUSE_UP, onDrag);
ball.addEventListener(MouseEvent.MOUSE_OUT, onDrag);
}
addChild(distantBackground);
distantBackground.y = stage.stageHeight - distantBackground.height;
distantBackground.width = stage.stageWidth;
setChildIndex(distantBackground,0);
addEventListener(Event.ENTER_FRAME, onGameLoop);
}
public function onGameLoop(e:Event):void{
//checkCollision();
for(var i:int=0;i<objectList.length;i++){
updatePhysics(i);
updateShadows(i,starLight);
}
}
public function updatePhysics(objRef:int):void{
if(lastXList[objRef] != undefined){
if(lastXList[objRef] != objectList[objRef].x){
xVelocityList[objRef] = objectList[objRef].x - lastXList[objRef];
}
}
if(lastYList[objRef]!= undefined){
if(lastYList[objRef] != objectList[objRef].y){
yVelocityList[objRef] = 4*(objectList[objRef].y - lastYList[objRef])/stage.frameRate;
}
}
if(objectList[objRef].y>= floor - objectList[objRef].height){
yVelocityList[objRef] = -(yVelocityList[objRef] * elasticityList[objRef]);
objectList[objRef].y = floor - objectList[objRef].height;
}
if(objectList[objRef].y<= 0){
yVelocityList[objRef] = -(yVelocityList[objRef] * elasticityList[objRef]);
objectList[objRef].y = 0;
}
if(objectList[objRef].x > (stage.stageWidth - objectList[objRef].width)){
xVelocityList[objRef]=-xVelocityList[objRef];
objectList[objRef].x = stage.stageWidth - objectList[objRef].width;
}
if (objectList[objRef].x <0){
xVelocityList[objRef]=-xVelocityList[objRef];
objectList[objRef].x = 0;
}
if(!dragList[objRef]){
yVelocityList[objRef]+=gravity;
objectList[objRef].y += yVelocityList[objRef];
xVelocityList[objRef]= (xVelocityList[objRef] * resistance);
if(-0.5<xVelocityList[objRef] && xVelocityList[objRef]<0.5){
xVelocityList[objRef] = 0;
}
objectList[objRef].x += xVelocityList[objRef];
}
lastXList[objRef] = objectList[objRef].x;
lastYList[objRef] = objectList[objRef].y;
if(xVelocityList[objRef] == 0){
xVelocityList[objRef]=randomMe(90,-90);
yVelocityList[objRef]=randomMe(90,-90);
}
}
public function onDrag(e:Event):void{
if(e.type == "mouseDown"){
setChildIndex(DisplayObjectContainer(e.target),numChildren - 1)
e.target.startDrag(false,bounding);
//xVelocityList[objRef] = yVelocityList[objRef] = 0;
//dragging = true;
}else{
e.target.stopDrag();
//dragging = false;
}
}
public function onLightDrag(e:Event):void{
if(e.type == "mouseDown"){
e.target.startDrag(false,bounding);
}else{
e.target.stopDrag();
}
}
public function updateShadows(objRef:int, lightSource:MovieClip):void{
//-----Cut for convenience------
}
public function checkCollision():void{
for(var v:int=0;v<objectList.length;v++){
var ball1 = objectList[v];
for(var w:int=v+1;w<objectList.length;w++){
var ball2 = objectList[w];
if((ball1.x + getRadius(ball1) + getRadius(ball2) > ball2.x) && (ball1.x < ball2.x + getRadius(ball1) + getRadius(ball2)) && (ball1.y + getRadius(ball1) + getRadius(ball2) > ball2.y) && (ball1.y < ball2.y + getRadius(ball1) + getRadius(ball2))){
var dx:Number = ball2.x - ball1.x;
var dy:Number = ball2.y - ball1.y;
var dist:Number = Math.sqrt((dx * dx) + (dy * dy));
if(dist < getRadius(ball1)+getRadius(ball2)){
var newX1:Number;
var newY1:Number;
var newX2:Number;
var newY2:Number;
trace("Magnitude 1 is : " + (Math.sqrt((xVelocityList[v] * xVelocityList[v]) + (yVelocityList[v] * yVelocityList[v]))));
trace("Magnitude 2 is : " + (Math.sqrt((xVelocityList[w] * xVelocityList[w]) + (yVelocityList[w] * yVelocityList[w]))));
newX1 = ((massList[v] * xVelocityList[v])+(massList[w] * xVelocityList[w]))/(massList[v] + massList[w]) * 2 - xVelocityList[v];
newY1 = ((massList[v] * yVelocityList[v])+(massList[w] * yVelocityList[w]))/(massList[v] + massList[w]) * 2 - yVelocityList[v];
newX2 = ((massList[v] * xVelocityList[v])+(massList[w] * xVelocityList[w]))/(massList[v] + massList[w]) * 2 - xVelocityList[w];
newY2 = ((massList[v] * yVelocityList[v])+(massList[w] * yVelocityList[w]))/(massList[v] + massList[w]) * 2 - yVelocityList[w];
xVelocityList[v] = newX1;
yVelocityList[v] = newY1;
xVelocityList[w] = newX2;
yVelocityList[w] = newY2;
ball1.x += newX1;
ball1.y += newY1;
ball2.x += newX2;
ball2.y += newY2;
}
}
}
}
}
public function randomMe(high:Number, low:Number = 0):Number{
return Math.random() * (high - low) + low;
}
public function getRadius(obj:MovieClip):Number{
return obj.width/2;
}
public function centerX(obj:MovieClip):Number{
return obj.x + getRadius(obj);
}
public function centerY(obj:MovieClip):Number{
return obj.y + getRadius(obj);
}
}
}
It's a very simple system to check for collision, just comparing the radius of the objects, and midair collisions seem fine, but if one ball lands on top of another that has no x or y velocity, it just sinks into it. Any ideas as to why?
I expect your balls behave like this: When one ball lands on top of the other, that's actually lying on the ground, the other ball gets pushed down into the ground, then you react at it within updatePhysics() by placing it into the position where it originated, thus, those balls become one within another. One of the suggestions that could remedy this will be to hold last collided object for each of the balls for one cycle of physics, say like this:
if(dist < getRadius(ball1)+getRadius(ball2)){
// process collision
ball1.lastCollided=ball2;
ball2.lastCollided=ball1;
}
Then, when you update your coordinates in updatePhysics(), check if lastCollided is null, if not, update that ball's coordinates and speed the same way, essentially simulating another collision. After checking for all the events within update physics cycle, assign null to lastCollided of all balls.

More than one bullet cant be on screen at once?

Basically what happens is when I shoot a bullet, it creates the bullet. However, if I click again while the bullet it still on screen, it removes the bullet and makes a completely new one. So now only one bullet can be on the screen at a time. How do I fix this?
The bullet in the library has the instance name of 'bullet'
package
{
public class GameEnter extends MovieClip
{
public function GameEnter()
{
addEventListener(MouseEvent.MOUSE_DOWN, shootBullet);
}
public var _bullet1:bullet = new bullet;
public var angleRadian = Math.atan2(mouseY - 300,mouseX - 300);
public var angleDegree = angleRadian * 180 / Math.PI;
public var speed1:int = 10;
public function shootBullet(evt:MouseEvent)
{
_bullet1.x = 300;
_bullet1.y = 300;
_bullet1.angleRadian = Math.atan2(mouseY - 300,mouseX -300);
_bullet1.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
addChild(_bullet1);
}
public function bulletEnterFrame(evt:Event)
{
var _bullet1 = evt.currentTarget;
_bullet1.x += Math.cos(_bullet1.angleRadian) * speed1;
_bullet1.y += Math.sin(_bullet1.angleRadian) * speed1;
_bullet1.rotation = _bullet1.angleRadian*180/Math.PI;
if (_bullet1.x < 0 || _bullet1.x > 600 || _bullet1.y < 0 || _bullet1.y > 600)
{
removeChild(_bullet1);
_bullet1.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
}
}
}
Well think about it, you store your _bullet1 variable in the class, which is fine, but every time you shoot you use the same variable and just change the x and y position again.
A better way to do this is to handle the animation for the bullet in the bullet class itself.
When you shoot, you just create a new bullet and add it to the stage.
In case you still want to use this way, it should be more like this:
public function shootBullet(evt:MouseEvent)
{
var bullet:bullet = new bullet();
bullet.x = 300;
bullet.y = 300;
bullet.angleRadian = Math.atan2(mouseY - 300,mouseX -300);
bullet.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
addChild(bullet);
}
public function bulletEnterFrame(evt:Event)
{
var tmpBullet:bullet = evt.currentTarget as bullet;
tmpBullet.x += Math.cos(_bullet1.angleRadian) * speed1;
tmpBullet.y += Math.sin(_bullet1.angleRadian) * speed1;
tmpBullet.rotation = _bullet1.angleRadian*180/Math.PI;
if (tmpBullet.x < 0 || tmpBullet.x > 600 || tmpBullet.y < 0 || tmpBullet.y > 600)
{
removeChild(tmpBullet);
tmpBullet.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
}
But the best way would be to go with option 1