How to change the direction of the ball when it hits the slanting line…
Like in mini golf game, the ball should move in some direction when it hits the wall…
i did it, but it works well for rectangle like shape,
but for diagonal its not working ie. the ball goes away in one direction…
i need to change the ball direction randomly but it should not go away from the wall…
package
{
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
public class ballMove extends MovieClip
{
private var dx:Number;
private var dy:Number;
private var dist:Number;
private var vx:Number;
private var vy:Number;
private var br:Number;
private var ballrolling:Boolean = false;
private var friction:Number = 0.98;
private var power:Number = 0.05;
private var hitAccuracy:Number = 5;
private var hitdistance:Number = 5;
private var xpos:Number;
private var ypos:Number;
private var angle:Number;
private var temppower:Number;
private var bounceAngle:Number;
private var bounceSpeed:Number;
private var container_mc:container;
private var wall1Rect:Rectangle;
private var wall2Rect:Rectangle;
private var wall3Rect:Rectangle;
private var wall4Rect:Rectangle;
private var ballRect:Rectangle;
public function ballMove()
{
container_mc= new container();
addChild(container_mc);
container_mc.x=400;
container_mc.y=300;
br= container_mc.ball.width / 2;
container_mc.addEventListener(Event.ENTER_FRAME, onEnter)
container_mc.addEventListener(MouseEvent.MOUSE_UP,mouseup)
}
private function onEnter(e:Event)
{
if (ballrolling)
{
container_mc.ball.x += vx;
container_mc.ball.y += vy;
//
vx *= friction;
vy *= friction;
//
if(container_mc.wall1.hitTestPoint((container_mc.ball.x+400),(container_mc.ball.y+300),true))
{
container_mc.ball.x = container_mc.ball.x + friction;
vx *= -1;
}
else if(container_mc.wall2.hitTestPoint((container_mc.ball.x+400),(container_mc.ball.y+300),true))
{
container_mc.ball.x = container_mc.ball.x - friction;
vx *= -1;
}
else if(container_mc.wall3.hitTestPoint((container_mc.ball.x+400),(container_mc.ball.y+300),true))
{
container_mc.ball.y = container_mc.ball.y + friction;
vy *= -1;
}
else if(container_mc.wall4.hitTestPoint((container_mc.ball.x+400),(container_mc.ball.y+300),true))
{
container_mc.ball.y = container_mc.ball.y - friction;
vy *= -1;
}
if (vx < 0.3 && vy < 0.3 && vx > -0.3 && vy > -0.3)
{
ballrolling = false;
}
}
}
private function mouseup(e:Event)
{
if (!ballrolling)
{
ballrolling = true;
rollBall();
}
}
private function rollBall()
{
dx = mouseX - (container_mc.ball.x+400);
dy = mouseY - (container_mc.ball.y+300);
temppower = Math.sqrt((dx * dx) + (dy * dy)) * power;
angle = Math.atan2(dy, dx);
vx = -1 * Math.cos(angle) * temppower;
vy = -1 * Math.sin(angle) * temppower;
}
}
}