Search code examples
actionscript-3flashactionscriptflash-cc

Actionsciprt 3 How to Accelerometer


I am about to create a 2D car racing game using accelerometer, The problem is the car position on the screen, that when the game starts, the car appears at the left side while expected to be at the center. How can I solve it?

private var accelerometer: Accelerometer;
    var accelX: Number;

    public function game() {
    if (Accelerometer.isSupported) {
        car.addEventListener(Event.ENTER_FRAME, moveCar);

        accelerometer = new Accelerometer();
        accelerometer.addEventListener(AccelerometerEvent.UPDATE, AccelerometerUpdateHandler);

    }
    }

    function AccelerometerUpdateHandler(event: AccelerometerEvent): void {
        accelX = event.accelerationX;
    }

    function moveCar(evt: Event) {
        car.x -= accelX * 30;

        if (car.x > 299) {
            car.x = 299;
        } else if (car.x < 110) {
            car.x = 110;
        }

    }

Solution

  • To centre a MovieClip to the stage at the start of app you need to get the stage width, divide this by 2 and then take away had of the car's width (unless the car is cent erred inside its MovieClip?)

    car.x = (stage.stageWidth /2) - (car.width /2)