Hi I am extremely new to coding in general and have been trying to improve my fluency. Thats why I started coding a pong game with Pygame because I wanted something visual. so I have created a pong design with working paddles and a ball that I have bouncing off walls but am having trouble getting the paddle collisions corect. I have it so it prints Paddle when my paddle and ball are aligned but it doesnt always detect it. How can I make it have more sensitivity and add bounce to the paddle. Once again I am very new so any syntax correction or advice on making the code easier to read or simplified would be great: the code is as follows :
import sys, pygame, pygame.mixer, random, math
from pygame.locals import *
pygame.init()
screen_size = width, height = 600, 400
black = 0,0,0
red = (200,0,0)
blue = 0,0,200
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("PONG WANNABE")
screen.fill(black)
paddle = pygame.image.load("paddle.png")
divider = pygame.image.load("divider.png")
def addVectors((angle1, length1), (angle2, length2)):
x = math.sin(angle1) * length1 + math.sin(angle2) * length2
y = math.cos(angle1) * length1 + math.cos(angle2) * length2
length = math.hypot(x, y)
angle = 0.5 * math.pi - math.atan2(y, x)
return (angle, length)
class Ball:
def __init__(self):
self.size = 8
self.x = width/2
self.y = height/2
self.colour = (255, 255, 255)
self.thickness = 0
self.speed = 0.05
self.angle = math.pi/2
def display(self):
pygame.draw.circle(screen,self.colour,int(self.x),int(self.y)),
self.size,self.thickness)
def move(self):
self.x += math.sin(self.angle) * self.speed
self.y -= math.cos(self.angle) * self.speed
def bounce(self):
if self.x > width - self.size:
self.x = 2*(width - self.size) - self.x
self.angle = - self.angle
elif self.x < self.size:
self.x = 2*self.size - self.x
self.angle = - self.angle
if self.y > height - self.size:
self.y = 2*(height - self.size) - self.y
self.angle = math.pi - self.angle
elif self.y < self.size:
self.y = 2*self.size - self.y
self.angle = math.pi - self.angle
ball = Ball()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_SPACE:
black = blue
elif event.type == KEYUP and event.key == K_SPACE:
black = 0,0,0
screen.fill(black)
mx,my = pygame.mouse.get_pos()
screen.blit(divider,(width/2, 0))
screen.blit(paddle,(10,my-35))
screen.blit(paddle,(width-20,365-my))
ball.move()
if ball.x < my + 73 and ball.x > my:
print "Paddle"
ball.bounce()
ball.display()
pygame.display.flip()
I would honestly try to use Rectangles and check if the Rectangles collide. Full documentation can be found at http://www.pygame.org/docs/ref/rect.html but I'll still explain directly how in your case.
In your Ball class you will probably want to create a Rect.
class Ball:
def __init__(self):
#all of your x, y etc.
#add in a react at the end of init
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
#self.size is the width and height
Then at the end of the function move you need to update the rect
def move(self):
#move ball with what you already have
#now update the rect
self.rect.x = x
self.rect.y = y
Now you'll want to create a rectangle for the paddle, now I dont know how wide your paddle is, but I'm going to just say 10 and you can adjust that as necessary.
So now to add the rectangle. In the while loop right after you get the x and y of the paddle add this line to create a rectangle
mrect = pygame.Rect(mx, my, 10, 73)
So now you have a rectangle to work with to check for a collide point. Now instead of this line if ball.x < my + 73 and ball.x > my: you need to change this to check for a collide point between your two rectangles. We're going to do this by using a function that is part of the class pygame.Rect called colliderect
So change the line if ball.x < my + 73 and ball.x > my: to this if ball.rect.colliderect(mrect): this will check if the rectangles, the ball or the paddle collide at any point.
Good luck!
This is for double ball pong. name ball instances circle_m and circle_mc. name paddle instances rectangle and rectangle_mc. name boundaries boundary1 and boundary. name goals goal1 and goal2. name text boxes textField_1,textField_2, and textField_3. Then use this code and have fun. (must be made in adobe flash obviously)
//1.
var xDir2 = 1;
var yDir2 = 1;
stage.addEventListener(Event.ENTER_FRAME, circleHit);
var xDir = 1;
var yDir = 1;
var score = 0;
var score2 = 0;
//2.
function circleHit(event:Event):void
{
{
circle_mc.x += 10 * xDir;
circle_mc.y += 10 * yDir;
circle_m.x += 5 * xDir2;
circle_m.y += 5 * yDir2;
if (circle_mc.hitTestObject(rectangle_mc))
{
xDir *= -1;
}
};
if (circle_mc.hitTestObject(rectangle))
{
xDir *= -1;
}
if (circle_mc.hitTestObject(boundary))
{
yDir *= -1;
}
if (circle_mc.hitTestObject(boundary1))
{
yDir *= -1;
}
if (circle_mc.hitTestObject(goal2))
{
score2++;
circle_mc.y = 161.95;
circle_mc.x = 273;
}
textField_2.text = score2;
textField_1.text = score;
if (circle_mc.hitTestObject(goal1))
{
score++;
circle_mc.y = 161.95;
circle_mc.x = 273;
}
if (circle_m.hitTestObject(goal2))
{
score2++;
circle_m.x = 273;
circle_m.y = 161.95;
}
if (circle_m.hitTestObject(goal1))
{
score++;
circle_m.x = 273;
circle_m.y = 161.95;
}
if (circle_m.hitTestObject(rectangle_mc))
{
xDir2 *= -1;
}
if (circle_m.hitTestObject(rectangle))
{
hSiz2 *= -2;
xDir2 *= -1;
}
if (circle_m.hitTestObject(boundary))
{
yDir2 *= -1;
}
if (circle_m.hitTestObject(boundary1))
{
yDir2 *= -1;
}
}
//This section creates variables to store the condition of each key A(up or down)
var keyUP:Boolean = false;
var keyDOWN:Boolean = false;
var keyRIGHT:Boolean = false;
var keyLEFT:Boolean = false;
This section creates event listeners. The first two check if any key has been pressed down or come back up. The third event listener controls a repeating loop
stage.addEventListener(KeyboardEvent.KEY_UP,key_Up);
stage.addEventListener(KeyboardEvent.KEY_DOWN,key_Down);
stage.addEventListener(Event.ENTER_FRAME,loop);
These functions changes the value of the variables if the key comes up.The switch statement; checks for which key is being processed. The case statements provide the options for each key with the number representing a key. break ends the case.
function key_Up(event:KeyboardEvent)
{
switch (event.keyCode)
{
case Keyboard.W :
keyLEFT = false;
break;
case 38 :
keyUP = false;
break;
case Keyboard.S :
keyRIGHT = false;
break;
case 40 :
keyDOWN = false;
}
}
function key_Down(event:KeyboardEvent)
{
switch (event.keyCode)
{
case Keyboard.W :
keyLEFT = true;
break;
case 38 :
keyUP = true;
break;
case Keyboard.S :
keyRIGHT = true;
break;
case 40 :
keyDOWN = true;
}
}
This function will repeat every time a frame is entered. It uses the values of the variables to control actions. The trace statement will display a word in the output window
function loop(event:Event)
{
if (keyUP)
{
rectangle_mc.y -= 20;
}
if (keyDOWN)
{
rectangle_mc.y -= -20;
}
if (keyLEFT)
{
rectangle.y -= 20;
}
if (keyRIGHT)
{
rectangle.y -= -20;
}
if (score ==10)
{
textField_3.text = "Left side WINS!!!!!";
circle_mc.y = -5000;
circle_mc.x = -5000;
}
if (score2 ==10)
{
textField_3.text = "Right side WINS!!!!!";
circle_mc.y = -5000;
circle_mc.x = -5000;
}
if (score ==10)
{
textField_3.text = "Left side WINS!!!!!";
circle_m.y = -5000;
circle_m.x = -5000;
}
if (score2 ==10)
{
textField_3.text = "Right side WINS!!!!!";
circle_m.y = -5000;
circle_m.x = -5000;
}
}
Related
I got this code off the internet for the game Pong to work on my AS3 document for my assignment. However i'm pretty much a beginner at code and i'm trying to get this game to work on mobile as the assignment needs a game to work on it.
Because it uses arrow keys, i would like to basically just replace them with buttons instead, one for going up and one for going down. I just don't know the type of code that would allow me to do that.
Something like, when button is pressed, player moves up or down depending which button, but im not sure where to replace the code and what to get rid of.
Here's the "Pong" class file:
package {
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Pong extends MovieClip {
//constants
private var pongUp:MovieClip = new PongUp ;
private var pongDown:MovieClip = new PongDown ;
const ballspeed:int = 10;
const playerspeed:int = 7;
const computerspeed:int = 10;
const computerIntelligence:int = 7;//intelligence is 7 out of 10
//global variables
var vx:int = - ballspeed;// x component of velocity of ball (velocity is speed with direction)
var vy:int = ballspeed;// y component of velocity of ball
var v1:int = 0;// initial velocity of player
var v2:int = 0;// initial velocity of computer
var playerScore:int = 0;
var computerScore:int = 0;
var player:MovieClip = new PongPlayer ;
var computer:MovieClip = new PongComputer ;
var ball:MovieClip = new PongBall ;
public function Pong() {
//init();
addEventListener(Event.ADDED_TO_STAGE,init);
}
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
stage.addEventListener(Event.ENTER_FRAME,EnterFrame);
addChild(player);
addChild(computer);
addChild(ball);
player.x = 23;
player.y = 300;
computer.x = 637;
computer.y = 311;
ball.x = 308;
ball.y = 328;
addChild(pongUp);
pongUp.x = 25;
pongUp.y = 700;
addChild(pongDown);
pongDown.x = 530;
pongDown.y = 700;
}
// this function resets the game
function reset():void {
player.y = stage.stageHeight / 2;
computer.y = stage.stageHeight / 2;
ball.x = stage.stageWidth / 2;
ball.y = stage.stageHeight / 2;
if (Math.abs(Math.random() * 2) > 1)
{
vx = - ballspeed;
}
else
{
vx = ballspeed;
}
if (Math.abs(Math.random() * 2) > 1)
{
vy = - ballspeed;
}
else
{
vy = ballspeed;
}
}
//pongDown.addEventListener ( MouseEvent.MOUSE_DOWN,moveDown );
//function moveDown ( e:MouseEvent ): void
//{
//}
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
//This function is executed when a frame changes
function EnterFrame(event:Event):void {
//variable decleration
var pHalfHeight = player.height / 2;// half height of player(used for collisions)
var pHalfWidth = player.width / 2;// half width of player (used for collisions)
var bHalfHeight = ball.height / 2;// half height of ball(used for collisions)
var bHalfWidth = ball.width / 2;// half width of ball (used for collisions)
//moving the player
player.y += v1;
//limiting the motion of player (it should not move beyond the stageheight)
if (player.y + pHalfHeight > stage.stageHeight)
{
player.y = stage.stageHeight - pHalfHeight;
}
else if (player.y - pHalfHeight < 0)
{
player.y = 0 + pHalfHeight;
}
//moving the ball
ball.x += vx;
ball.y += vy;
//moving the computer automatically
if (Math.abs(Math.random() * 10) < computerIntelligence)
{
var d:int = computer.y - ball.y;
if (Math.abs(d) > pHalfHeight)
{
if ((d > 0))
{
v2 = - computerspeed;
}
else
{
v2 = computerspeed;
}
}
}
computer.y += v2;
//limiting the motion of computer (it should not move beyond the stageheight)
if (computer.y + pHalfHeight > stage.stageHeight)
{
computer.y = stage.stageHeight - pHalfHeight;
}
else if (computer.y - pHalfHeight < 0)
{
computer.y = 0 + pHalfHeight;
}
//collision with horizontal walls
if (ball.y + bHalfHeight >= stage.stageHeight || ball.y - bHalfHeight <= 0)
{
vy *= -1;
}
//collision with player and computer
if (ball.x - bHalfWidth <= player.x + pHalfWidth)
{
if (Math.abs(ball.y - player.y) <= pHalfHeight)
{
vx = ballspeed;
if ((v1 != 0))
{
vy = 2 * v1;
}
}
}
else if (ball.x + bHalfWidth >= computer.x - pHalfWidth)
{
if (Math.abs(ball.y - computer.y) <= pHalfHeight)
{
vx = - ballspeed;
if ((v2 != 0))
{
vy = v2;
}
}
}
//collision with vertical walls & updating scores
if (ball.x + bHalfWidth >= stage.stageWidth)
{
playerScore += 1;
reset();
}
else if (ball.x - bHalfWidth <= 0)
{
computerScore += 1;
reset();
}
//display the score on the textfield
//txtPlayer.text = String(playerScore);
//txtComputer.text = String(computerScore);
}
}
}
For mobile, you'll want to compile using AIR for Android or iOS. You can then replace:
//this function sets the velocity of player when key is pressed
function KeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP)
{
v1 = - playerspeed;
}
else if (event.keyCode == Keyboard.DOWN)
{
v1 = playerspeed;
}
}
//this function sets the velocity of player to 0 if key is released
function KeyUp(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
v1 = 0;
}
}
with:
function KeyDown(event:TouchEvent):void {
if (event.stageY < player.y){
v1 = - playerspeed;
}else if (event.stageY > player.y){
v1 = playerspeed;
}
}
function KeyUp(event:TouchEvent):void {
v1 = 0;
}
Then replace:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
with:
//this function will add all event listeners
function init(e:Event):void {
stage.addEventListener(TouchEvent.TOUCH_BEGIN, KeyDown);
stage.addEventListener(TouchEvent.TOUCH_END, KeyUp);
And make sure to use TouchEvent instead of KeyboardEvent by replacing:
import flash.events.KeyboardEvent;
with:
import flash.events.TouchEvent;
Now when you hold your finger down on the screen, the "player" will move towards that Y location. If your game is using the X axis, just change the Ys to Xs!
Hope this helps!
I would like to know how to make a smooth jump in my game. Its a 2D game and the code is really simple but I would want to know how to make it better for it to slow down when it gets to the max height and then smooth drop.
This is all I have for jumping:
Player.y -= 50;
Your best bet would be to use a physics engine (Box2d etc). If you don't want the overhead of one though (if the only thing you'd use it for is jumping and not collisions) then you just need to add some friction to your logic.
var friction :Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity :Number = 50; //how much to move every increment, reset every jump to default value
var direction :int = -1; //reset this to -1 every time the jump starts
function jumpLoop(){ //lets assume this is running every frame while jumping
player.y += velocity * direction; //take the current velocity, and apply it in the current direction
if(direction < 0){
velocity *= friction; //reduce velocity as player ascends
}else{
velocity *= 1 + (1 - friction); //increase velocity now that player is falling
}
if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
if(player.y > stage.stageHeight - player.height){ //stage.stageheight being wherever your floor is
player.y = stage.stageHeight - player.height; //put player on the floor exactly
//jump is over, stop the jumpLoop
}
}
Copy/paste the following code... jump() can be replaced by jump2() (without bouncing effect). The jumping will be produced by the space bar:
const FA:Number = .99; // air resistance
const CR_BM:Number = .8; // bouncing coefficient
const µ:Number = .03; // floor friction
const LB:int = stage.stageHeight; // floor (bottom limit)
const G:int = 2.5; // gravity
const R:int = 50;
var ball:MovieClip = new MovieClip();
this.addChild(ball);
var ba:* = ball.graphics;
ba.beginFill(0xFFCC00);
ba.lineStyle(0, 0x666666);
ba.drawCircle(0, 0, R);
ba.endFill();
ball.vx = 2;
ball.vy = -30;
ball.r = R;
ball.x = 100;
ball.y = LB - R;
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
function myKeyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.SPACE) {
ball.vy = -30;
addEventListener(Event.ENTER_FRAME, jump);
}
}
function jump(e:Event):void {
ball.vy = ball.vy + G;
ball.vx *= FA;
ball.vy *= FA;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y > LB - ball.r) {
ball.y = LB - ball.r;
ball.vy = -1 * ball.vy * CR_BM;
ball.vx += ball.vx * - µ;
}
}
/*
function jump2(e:Event):void {
ball.vy = ball.vy + G;
ball.vx *= FA;
ball.vy *= FA;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y > LB - ball.r) {
ball.y = LB - ball.r;
}
}
*/
What code should I put in here to make my ship stay in the stage?
My ship keeps going off the stage when I press the keys and it goes too far. How do I get it to bump into walls and make it stay on the stage?
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Ship extends MovieClip{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
function Ship(){
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
}
function kill(){
var explosion = new Explosion();
stage.addChild(explosion);
explosion.x = this.x;
explosion.y = this.y;
removeEventListener("enterFrame", move);
this.visible = false;
Game.gameOver();
}
function takeDamage(d){
health -= d;
if(health<=0){
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
}
function move(e:Event){
shootLimiter += 1;
if(Key.isDown(Keyboard.D)){
this.x = this.x + velocity;
}
if(Key.isDown(Keyboard.A)){
this.x = this.x - velocity;
}
if(Key.isDown(Keyboard.W)){
this.y = this.y - velocity;
}
if(Key.isDown(Keyboard.S)){
this.y = this.y + velocity;
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8){
shootLimiter = 0;
var b = new Bullet();
stage.addChild(b);
b.x = this.x + 40;
b.y = this.y + -25;
}
if(shield.visible == true){
shield.alpha -= 0.0005;
if(shield.alpha == 0){
shield.visible = false;
shield.alpha = 1;
}
}
}
}
}
Your code is hard to fix as it is, but I'll give you an answer in pseudo, so you could think on how to implement it to fit in your project. Your ship is going out of the frame because it has no notion of where to stop. Lets say the ship x and y coordinates are taken from the upper left corner of the sprite, as it is in actionscript, then, every time your ship moves to the left, you must consider the following:
if(Key.isDown(Keyboard.A)){
var futureX:Number = this.x - velocity;
if (futureX <= 0){ //your ship has reached the left border of the screen
this.x = 0;
} else {
this.x = futureX;
}
}
things get a little more complicated when you're checking for the right or bottom border of the screen, as you need to consider the size of your stage and the size of your sprite in the calculations:
if(Key.isDown(Keyboard.S)){
var futureY:Number = this.y + velocity;
if (futureY + this.height >= Stage.stageHeight){
this.y = Stage.stageHeight - this.height;
} else {
this.y = futureY;
}
}
The solution for the top and right borders are trivial after this.
I'm trying to make a game, following this tutorial.
The issue comes from the fact that I am using ActionScript 3.0 whereas the tutorial was written using ActionScript 2.0.
Regarding the sight of the enemy, I have turned this code:
onClipEvent (enterFrame) {
dist_x = _root.hero._x-_x;
dist_y = _root.hero._y-_y;
dist = Math.sqrt(dist_x*dist_x+dist_y*dist_y);
angle = Math.atan(dist_y/dist_x)/(Math.PI/180);
if (dist_x<0) {
angle += 180;
}
if (dist_x>=0 && dist_y<0) {
angle += 360;
}
wall_collision = 0;
for (x=1; x<=dist; x++) {
point_x = _x+x*Math.cos(angle*Math.PI/180);
point_y = _y+x*Math.sin(angle*Math.PI/180);
if (_root.wall.hitTest(point_x, point_y, true)) {
wall_collision = 100;
break;
}
}
_root.line._x = _x;
_root.line._y = _y;
_root.line._rotation = angle;
_root.line._alpha = 100-wall_collision;
}
Into that:
// calculate rotation based on target
_dx = this.x - _root.hero.x;
_dy = this.y - _root.hero.y;
// which way to rotate
_rotateTo = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (_rotateTo > barrel.rotation + 90) _rotateTo -= 360;
if (_rotateTo < barrel.rotation - 90) _rotateTo += 360;
// ease rotation
_trueRotation = (_rotateTo - barrel.rotation) / _rotateSpeedMax;
// update rotation
barrel.rotation += _trueRotation;
wall_collision = 0;
OuterLoop: for (var xi=1; xi<=_dx; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_rotateTo);
var point_y:Number = this.y + xi*Math.sin(_rotateTo);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation += _trueRotation;
_root.sight.alpha = 100 - wall_collision;
But the it does not work.
The rotation do work fine, but the whole "alpha = 0 if player is behind a wall" does not work.
Please help me resolving the issue.
Try the following:
// calculate rotation based on target
_dx = _root.hero.x-this.x;
_dy = _root.hero.y-this.y;
// The full distance is missing from your AS3 code
_dist = Math.sqrt(_dx*_dx+_dy*_dy);
// Return the old good approach for finding angle
angle = Math.atan(_dy/_dx)/(Math.PI/180);
if (_dx<0) {
_angle += 180;
}
if (_dx>=0 && _dy<0) {
_angle += 360;
}
wall_collision = 0;
OuterLoop: for (var xi=1; xi<=_dist; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_angle*Math.PI/180);
var point_y:Number = this.y + xi*Math.sin(_angle*Math.PI/180);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation = _angle;
// Alpha changed from [0, 100] scale to [0, 1] scale.
_root.sight.alpha = (100 - wall_collision) * 0.01;
Information on alpha in ActionScript 3.0.
As per AS3 reference, alpha is from 0 to 1, not 0 to 100. That would suggest
`_root.sight.alpha = (100 - wall_collision)/100.0´
might work.
Can You try the following code. I have no prev exp with flash, but seems like You missed something.
The iterator xi should take values in range of distance, not only by one axis dx.
// calculate rotation based on target
_dx = this.x - _root.hero.x;
_dy = this.y - _root.hero.y;
// the iteration is by distance in original article mentioned so
// keep dist
//=================================
_dist = Math.sqrt(_dx*_dx+_dy*_dy);
// which way to rotate
_rotateTo = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (_rotateTo > barrel.rotation + 90) _rotateTo -= 360;
if (_rotateTo < barrel.rotation - 90) _rotateTo += 360;
// ease rotation
_trueRotation = (_rotateTo - barrel.rotation) / _rotateSpeedMax;
// update rotation
barrel.rotation += _trueRotation;
wall_collision = 0;
// xi iterations are to a distance
//== =======
OuterLoop: for (var xi=1; xi<=_dist; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_rotateTo);
var point_y:Number = this.y + xi*Math.sin(_rotateTo);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation += _trueRotation;
// EDITED AFTER OTHERS SOLVED
// was
//_root.sight.alpha = 100 - wall_collision;
// should be:
// Alpha changed from [0, 100] scale to [0, 1] scale.
_root.sight.alpha = (100 - wall_collision) * 0.01;
// END OF SOLUTION
There is only slight modification to Your original code, marked by preceding //=====
EDIT:
And the winner is transparency range. Still, I do recommend to iterate to a distance, not to _dx.
I having some problem with bullet and enemy. I don't think i need to explain so much, just take a look at the code. Im not very good at AS3, im new and learning so I need help :P
Ok, this is on the flash/stage timeline. Here I say if I press mouse a bullet should be created.
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(pEvent)
{
// Create a new bullet
var b = new Bullet();
// Set his position to the tank position
b.x = Player.x;
b.y = Player.y;
// Save the randian angle between the mouse and the tank
// This angle will set the direction of the bullet
b.angleRadian = Math.atan2(AIM.y - Player.y,AIM.x - Player.x);
// Add an enter frame event on each bullet
b.addEventListener(Event.ENTER_FRAME, bulletEnterFrame);
// Add this display object on the display list
addChild(b);
}
// Velocity of each bullet
var speed = 8;
function bulletEnterFrame(pEvent)
{
// Get the current object (Bullet)
var b = pEvent.currentTarget;
// Move this bullet on each frames
// On X axis use the cosinus angle
b.x += Math.cos(b.angleRadian) * speed;
// On Y axis use the sinus angle
b.y += Math.sin(b.angleRadian) * speed;
// Orient the bullet to the direction
b.rotation = b.angleRadian * 180 / Math.PI;
// You have to remove each created bullet
// So after every moves you must check bullet position
// If the bullet is out of the screen
if (b.x < 0 || b.x > 1024 || b.y < 0 || b.y > 768)
{
// Remove it from the display list
removeChild(b);
// /!\ AND REOMOVE HIS EVENT LISTER
b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
if (b.hitTestObject(Enemy))
{
**I WANT TO REMOVE ENEMY!!!!**
}
}
OK. And on timeline i also create enemys. Like this:
var Enemy:MovieClip = new AI(stage);
addChild(Enemy);
And the enemyclass looks like this:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
public class AI extends MovieClip
{
var speed:Number = 1;
var distance:Number;
public function AI(stage):void
{
addEventListener(Event.ENTER_FRAME, onadd);
}
public function onadd(e:Event):void
{
addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void
{
var Player = MovieClip(root).Player;
var yDistance:Number = Player.y - y;
var xDistance:Number = Player.x - x;
if (Math.sqrt(yDistance*yDistance + xDistance*xDistance) < speed)
{
x = Player.x;
y = Player.y;
}
else
{
var radian:Number = Math.atan2(yDistance,xDistance);
x += Math.cos(radian) * speed;
y += Math.sin(radian) * speed;
rotation = radian * 180 / Math.PI;
}
if (this.hitTestObject(Player))
{
trace("DEAD");
}
//distance = Math.sqrt( ( MovieClip(root).Player.x - this.x ) * ( MovieClip(root).Player.x - this.x ) + ( MovieClip(root).Player.y - this.y ) * ( MovieClip(root).Player.y - this.y ) );
}
}
}
The think is that I can't figure out how I should remove enemy when bullet hits hit.
Please help!
Just use removeChild.
if (b.hitTestObject(Enemy))
{
//**I WANT TO REMOVE ENEMY!!!!**
removeChild(Enemy);
}
if (b.x < 0 || b.x > 1024 || b.y < 0 || b.y > 768)
{
// Remove it from the display list
removeChild(b);
// /!\ AND REOMOVE HIS EVENT LISTER
b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
}
You are removing the child, then trying to access an event with the child.
Try
if (b.x < 0 || b.x > 1024 || b.y < 0 || b.y > 768)
{
b.removeEventListener(Event.ENTER_FRAME, bulletEnterFrame);
removeChild(b);
}