Пример #1
0
int map::destroyLines()
{
	int pocet = 0;

	for (int y = 0; y < HEIGHT; y++)
	{
		bool good = true;

		for (int x = 0; x < WIDTH; x++)
		{
			if (!data[y][x])
			{
				good = false;

				break;
			}
		}

		if (good)
		{
			for (int x = 0; x < WIDTH; x++)
			{
				data[y][x] = 0;
			}

			applyGravity(y);
			pocet++;

			y = 0;
		}
	}

	return pocet;
}
Пример #2
0
	void Moveable::applyPhysics(const UpdateContext& context, std::vector<pf::GameEntity*>& collisions)
	{
		pf::PhysicsInfo info;
		sf::Vector2f currentVelocity = _physicsInfo.getVelocity();
		sf::Vector2f currentAcceleration = _physicsInfo.getAcceleration();

		info.setVelocity(currentVelocity.x, currentVelocity.y);
		info.setAcceleration(currentAcceleration.x, currentAcceleration.y);

		applyMovement(context, &info);

		applyGravity(context, &info);

		checkCollisions(collisions, &info);

		sf::Vector2f newPosition = info.apply(getX(), getY(), context.elapsedTime);

		arrangePosition(newPosition);

		setPosition(newPosition.x, newPosition.y);

		if(_isJumping)
		{
			_jumpFrames++;
		}
	}
Пример #3
0
void ParticleSystem::update(float dt)
{
	aging(dt);
	applyGravity();
	for (vector<Particle*>::iterator iter = particles.begin(); iter != particles.end(); iter++)
	{
		(*iter)->position = (*iter)->position + (*iter)->velocity*dt;
		(*iter)->velocity = (*iter)->velocity + (*iter)->acceleration*dt;
	}
}
Пример #4
0
void Sphere::jump(){
    GLdouble time = clock();

    _nextPosY = _velocity*(sin(_angleParabolicMove))*_timeJump  +_initPosY;

    applyGravity();

    manageJumpRotation();
    //----------------"delay" 0.01 seg--------------------
    while ((clock() - time) < 0.01*CLOCKS_PER_SEC){}
    //----------------------------------------------------

}
void PhysicsComponent::update(double delta) {

    timeDelta = delta;
    if (useGravity) applyGravity();
    if (useFriction) applyFriction();
    
    
    force = checkForce(force);
    
    movement = (impulse+force)*timeDelta;

    applyMove(movement, true);
    
    impulse = Vec2(0,0);

}
Пример #6
0
int	btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep)
{
	startProfiling(timeStep);

	BT_PROFILE("stepSimulation");

	int numSimulationSubSteps = 0;

	if (maxSubSteps)
	{
		//fixed timestep with interpolation
		m_localTime += timeStep;
		if (m_localTime >= fixedTimeStep)
		{
			numSimulationSubSteps = int( m_localTime / fixedTimeStep);
			m_localTime -= numSimulationSubSteps * fixedTimeStep;
		}
	} else
	{
		//variable timestep
		fixedTimeStep = timeStep;
		m_localTime = timeStep;
		if (btFuzzyZero(timeStep))
		{
			numSimulationSubSteps = 0;
			maxSubSteps = 0;
		} else
		{
			numSimulationSubSteps = 1;
			maxSubSteps = 1;
		}
	}

	//process some debugging flags
	if (getDebugDrawer())
	{
		btIDebugDraw* debugDrawer = getDebugDrawer ();
		gDisableDeactivation = (debugDrawer->getDebugMode() & btIDebugDraw::DBG_NoDeactivation) != 0;
	}
	if (numSimulationSubSteps)
	{

		//clamp the number of substeps, to prevent simulation grinding spiralling down to a halt
		int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps)? maxSubSteps : numSimulationSubSteps;

		saveKinematicState(fixedTimeStep*clampedSimulationSteps);

		applyGravity();

		

		for (int i=0;i<clampedSimulationSteps;i++)
		{
			internalSingleStepSimulation(fixedTimeStep);
			synchronizeMotionStates();
		}

	} else
	{
		synchronizeMotionStates();
	}

	clearForces();

#ifndef BT_NO_PROFILE
	CProfileManager::Increment_Frame_Counter();
#endif //BT_NO_PROFILE
	
	return numSimulationSubSteps;
}
Пример #7
0
//
// This method is a modified version of the FluidSimulator2d::updateVelocity
// method to reflect sand behavior
//
void SandSimulator2d::updateVelocity( float dt )
{
	//FluidSimulator2d::updateVelocity(dt);
	//return;

	// store the velocity in the oldVelocity member of each cell so that we later can compute the change in velocity --------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
		(*it).second.oldVelocity = (*it).second.velocity;

	// if advection is not done through particles (PIC/FLIP)
	if( !particleBasedAdvection )
		// then we use a sem-lagrange method to advect velocities...
		advectGridVelocities( dt );

	// apply external forces ----------------------------------
	applyGravity( dt, 0.0f, -9.1f );


	// apply viscosity ----------------------------------------
	solveViscosity( dt );




	// extrapolate velocities into surrounding buffer cells ------
	extrapolateVelocities();
	// set Boundary conditions -------
	setBoundaryConditions();


	// solve for pressure and make the velocity grid divergence free ----
	solvePressure( dt );

	// extrapolate velocity into buffer cells second time -----------------
	extrapolateVelocities();
	// set solid cell velocities ------------------------------
	setBoundaryConditions();

	// sand
	applySandModel( dt );

	// extrapolate velocity into buffer cells second time -----------------
	//extrapolateVelocities();
	// set solid cell velocities ------------------------------
	//setBoundaryConditions();



	// compute the change in velocity using the oldVelocity member which we have stored at the beginning of this procedure ----------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		(*it).second.velocityChange.x = (*it).second.velocity.x - (*it).second.oldVelocity.x;
		(*it).second.velocityChange.y = (*it).second.velocity.y - (*it).second.oldVelocity.y;
	}


	// if advection is not done through particles (PIC/FLIP)
	if( particleBasedAdvection )
	{
		// update the velocities of the particles from the grid --------------------------------------
		for( std::vector<Particle2d>::iterator it=markerParticles.begin(); it != markerParticles.end(); ++it )
		{
			// the solution of PIC and FLIP are blended together according to a specified blendweight
			// FLIP
			math::Vec2f flipVelocity = (*it).velocity + getVelocityChange( (*it).position.x, (*it).position.y );
			// PIC
			math::Vec2f picVelocity = getVelocity( (*it).position.x, (*it).position.y );
			// FINAL
			(*it).velocity = PICFLIPWeight*flipVelocity + (1.0f - PICFLIPWeight)*picVelocity;
		}
	}
}
Пример #8
0
//
// This method is a modified version of the FluidSimulator2d::updateVelocity
// method to reflect viscoelastic behavior
//
void ViscoElasticFluid2d::updateVelocity( float dt )
{
	//FluidSimulator2d::updateVelocity(dt);
	//return;

	// store the velocity in the oldVelocity member of each cell so that we later can compute the change in velocity --------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
		(*it).second.oldVelocity = (*it).second.velocity;

	// update total strain for each fluid cell ------------------------------------------------------------------------------
	// calculate T and accumulate new strain in E
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		Cell *cell = &(*it).second;

		if( cell->type != Cell::Fluid )
			continue;

		// first term T
		math::Matrix22f D = computeStrainRateTensor( cell );

		cell->strainTensor += dt*D;

		// second term -kyr*...
		float norm = math::frobeniusNorm( cell->strainTensor );
		math::Matrix22f plasticYielding = math::Matrix22f::Zero();
		if( norm )
			plasticYielding = plasticYieldRate*std::max<float>( 0, norm - elasticYieldPoint )*cell->strainTensor*(1.0f / norm);

		cell->strainTensor -= dt*plasticYielding;
	}

	// advect elastic strain tensor E -------------------------------------------------------------------------------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
		// clear temp variable for the intermediate result
		(*it).second.temp = math::Matrix22f::Zero();

	// now advect the tensor components for each fluid-cell
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		Cell *cell = &(*it).second;

		float e11, e22, e12;


		e11 = cell->strainTensor.m[0][0];
		e22 = cell->strainTensor.m[1][1];
		e12 = cell->strainTensor.m[0][1];

		if(cell->type == Cell::Fluid)
		{
			// track strain tensor components which lie at the cell center -> E[1][1] && E[2][2]
			math::Vec2f centerPos = traceParticle( math::Vec2f( (*it).first.i * cellSize+(cellSize/2.0f), (*it).first.j * cellSize+(cellSize/2.0f) ), dt );
			e11 = getInterpolatedStrainTensorComponent( centerPos.x/cellSize - 0.5f, centerPos.y/cellSize - 0.5f, 0, 0 );
			e22 = getInterpolatedStrainTensorComponent( centerPos.x/cellSize - 0.5f, centerPos.y/cellSize - 0.5f, 1, 1 );
		}

		if( cell->xNeighboursFluid || cell->yNeighboursFluid )
		{
			// track strain tensor components which lie at the cell edges -> E[1][2]
			math::Vec2f offPos = traceParticle( math::Vec2f( (*it).first.i * cellSize, (*it).first.j * cellSize ), dt );
			e12 = getInterpolatedStrainTensorComponent( offPos.x/cellSize, offPos.y/cellSize, 0, 1 );
		}

		cell->temp.m[0][0] = e11;
		cell->temp.m[1][1] = e22;
		cell->temp.m[0][1] = e12;
		cell->temp.m[1][0] = e12;

	}

	// copy the intermediate results to the final values
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		if( (*it).second.type == Cell::Fluid )
			(*it).second.strainTensor = (*it).second.temp;
		else
			(*it).second.strainTensor = (*it).second.temp;
	}

	// extrapolate elastic strain into air
	extrapolateStrain();

	// advect velocities (if advection is not done through particles (PIC/FLIP) ) --------------------------------
	if( !particleBasedAdvection )
		// then we use a sem-lagrange method to advect velocities...
		advectGridVelocities( dt );

	// apply external forces ------------------------------------------------------------------------------------
	applyGravity( dt, 0.0f, -9.1f );


	/*
	// stretch test
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		Cell *cell = &it->second;

		// we have to advance velocity-components of all cells which border fluid cells
		if( cell->xNeighboursFluid )
		{
		if( cell->center.x > 0.6f )
		{
			cell->velocity.x += 10.0f*dt;
			//cell->velocity.y += 0.0f;
		}else
		if( cell->center.x < 0.4f )
		{
			cell->velocity.x += -10.0f*dt;
			//cell->velocity.y += 0.0f;
		}
		}
	}
	*/


	// apply elastic strain force to u -----------------------------------------------------------------------------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		Cell *cell = &(*it).second;

		cell->vonMisesEquivalentStress = 0.0f;

		if( cell->xNeighboursFluid || cell->yNeighboursFluid )
		{
			math::Vec2f f = elasticModulus*computeDivE( cell );

			if( cell->xNeighboursFluid )
				cell->velocity.x += dt*f.x;
			if( cell->yNeighboursFluid )
				cell->velocity.y += dt*f.y;

			// compute equivalent stress
			cell->stressTensor = -elasticModulus*cell->strainTensor;
			cell->vonMisesEquivalentStress = sqrt( 3.0f/2.0f ) * math::frobeniusNorm( cell->stressTensor );
		}
	}



	// apply viscosity ----------------------------------------------------
	solveViscosity( dt );




	// extrapolate velocities into surrounding buffer cells ---------------
	extrapolateVelocities();
	// set Boundary conditions --------------------------------------------
	setBoundaryConditions();


	// solve for pressure and make the velocity grid divergence free ------
	solvePressure( dt );

	// extrapolate velocity into buffer cells second time -----------------
	extrapolateVelocities();
	// set solid cell velocities ------------------------------------------
	setBoundaryConditions();

	

	// compute the change in velocity using the oldVelocity member which we have stored at the beginning of this procedure ----------
	for( stdext::hash_map<Cell::Coordinate, Cell, hash_compare>::iterator it = gridCells.begin(); it != gridCells.end(); ++it )
	{
		(*it).second.velocityChange.x = (*it).second.velocity.x - (*it).second.oldVelocity.x;
		(*it).second.velocityChange.y = (*it).second.velocity.y - (*it).second.oldVelocity.y;
	}

	// if advection is not done through particles (PIC/FLIP)
	if( particleBasedAdvection )
	{
		// update the velocities of the particles from the grid --------------------------------------
		for( std::vector<Particle2d>::iterator it=markerParticles.begin(); it != markerParticles.end(); ++it )
		{
			// the solution of PIC and FLIP are blended together according to a specified blendweight
			// FLIP
			math::Vec2f flipVelocity = (*it).velocity + getVelocityChange( (*it).position.x, (*it).position.y );
			// PIC
			math::Vec2f picVelocity = getVelocity( (*it).position.x, (*it).position.y );
			// FINAL
			(*it).velocity = PICFLIPWeight*flipVelocity + (1.0f - PICFLIPWeight)*picVelocity;
		}
	}

}
void Jumpman::simulateSelf(double deltaTime)
{
    mDeltaTime = deltaTime;

    //Build acceleration vector.
    mAcceleration = glm::vec3(0.0f, 0.0f, 0.0f);

    //Get speed velocity components
    float forwardVelocity = glm::dot(mVelocity, mOrientation.getForward());
    float rightVelocity = glm::dot(mVelocity, mOrientation.getRight());
    float upVelocity = glm::dot(mVelocity, mOrientation.getUp());

    float forwardAccel = 0.0;
    float rightAccel = 0.0;
    float upAccel = 0.0;
    float aimAccel = 0.0;

    //If the direction we want to move is the opposite of the direction we are currently moving, then acceleration is increased.
    int currentForwardMovement = 0;
    int currentRightMovement = 0;

    //Don't bother accelerating if we are already going too fast.
    bool canMoveForward = true;
    if(mForwardMovement == 1)
    {
        if(forwardVelocity < -sGroundMaxSpeed || !mCanMoveForward)
            canMoveForward = false;
    }
    else if(mForwardMovement == -1)
    {
        if(forwardVelocity > sGroundMaxSpeed || !mCanMoveBackward)
            canMoveForward = false;
    }

    bool canMoveRight = true;
    if(mRightMovement == 1)
    {
        if(rightVelocity > sGroundMaxSpeed || !mCanMoveRight)
            canMoveRight = false;
    }
    else if(mRightMovement == -1 )
    {
        if(rightVelocity < -sGroundMaxSpeed || !mCanMoveLeft)
            canMoveRight = false;
    }

    if(forwardVelocity < 0) currentForwardMovement = 1;
    if(forwardVelocity > 0) currentForwardMovement = -1;

    if(canMoveForward)
        std::cout << "TRUE" << std::endl;
    else
        std::cout << "FALSE" << std::endl;

    if(mForwardMovement != 0 && canMoveForward)
    {
        if(mForwardMovement != 0 && currentForwardMovement != 0 && mForwardMovement != currentForwardMovement)
        {
            forwardAccel = sGroundDeaccel;
        }
        else
        {
            forwardAccel = sGroundAccel;
        }
        forwardAccel *= mForwardMovement;
    }
    else if(mForwardMovement == 0)
    {
        forwardAccel = 0.0f;
    }

    if(rightVelocity > 0) currentRightMovement = 1;
    if(rightVelocity < 0) currentRightMovement = -1;

    if(mRightMovement != 0 && canMoveRight)
    {
        if(mRightMovement != 0 && currentRightMovement != 0 && mRightMovement != currentRightMovement) rightAccel = sGroundDeaccel;
        else  rightAccel = sGroundAccel;
        rightAccel *= mRightMovement;
    }
    else if(mRightMovement == 0)
    {
        rightAccel = 0;
    }

    if(mJumpTimerAll > 0.0)
    {
        mJumpTimerAll -= deltaTime;
    }

    if((mIsGrounded || mAttached) && mCanJump && mJumpTimerAll <= 0)
    {
        if(mJumpTimerGround > 0.0 && upVelocity <= 0.0f)
        {
            mJumpTimerGround -= deltaTime;
            if(mJumpTimerGround < 0.0) mJumpTimerGround = 0.0;
        }

        if(mJumping && mJumpTimerGround <= 0.0)
        {
            mVelocity += sJumpAccel * mOrientation.getUp() ;
            mJumpTimerGround = sJumpCooldownGround;
            mJumpTimerAll = sJumpCooldownAir;
            mAttached = false;
            mIsGrounded = false;
        }
        else if(mLeaping && mJumpTimerGround <= 0.0)
        {
            mVelocity -= sLeapAccel * mAim;
            mJumpTimerGround = sJumpCooldownGround;
            mJumpTimerAll = sJumpCooldownAir;
            mAttached = false;
            mIsGrounded = false;
        }
    }

    //Climbing Code

    glm::vec3 myWorldPos = mOrientation.getPos();
    if(mClimbing)
    {
        //If not already attached to something, attempt to climb.
        if(mClimable && !mAttached && !mAttemptingToClimb)
        {
            glm::vec3 vectorToClimbPoint = mClimableCoord - myWorldPos;
            float distanceToClimbPoint = glm::length(vectorToClimbPoint);

            if(distanceToClimbPoint <= sLungeRange)
            {
                //Lunge towards the climbpoint if out of range.
                if(distanceToClimbPoint > sGrabRange)
                {
                    mVelocity += glm::normalize(vectorToClimbPoint) * sLungeVelocity;

                }

                std::cout << "Attempting to Climb" << std::endl;
                mAttemptingToClimb = true;
                mTimeAttemptingToClimb = 0.0;

                mClimbTarget = mClimableCoord;
            }


        }
        //Detach if attached.
        else if(mAttached)
        {
            mAttached = false;
        }
    }

    if(mAttemptingToClimb && !mClimbing)
    {
        glm::vec3 vectorToClimbPoint = mClimbTarget - myWorldPos;
        float speedTowardsPoint = glm::dot(vectorToClimbPoint, mVelocity);
        float distanceToClimbPoint = glm::length(vectorToClimbPoint);
        std::cout << distanceToClimbPoint << std::endl;
        if(distanceToClimbPoint <= sGrabRange)
        {
            //if(!(speedTowardsPoint < 0))
            {
                mVelocity = glm::vec3(0.0f); //Kill all movement
                mAcceleration = glm::vec3(0.0f);

                if(distanceToClimbPoint < sGrabRange) //Make sure don't get sucked into wall
                {
                    float rollbackDistance = sGrabRange - distanceToClimbPoint;
                    glm::vec3 rollbackVector = rollbackDistance * (-glm::normalize(vectorToClimbPoint));
                    mOrientation.translate(rollbackVector);
                }

                mAttached = true;
                mAttemptingToClimb = false;

                //mOrientation.translate(mBounceVelocity.x*deltaTime, mBounceVelocity.y*deltaTime, mBounceVelocity.z*deltaTime);
                mBounceVelocity = glm::vec3(0.0f);
            }


        }
        else
        {
            mTimeAttemptingToClimb += deltaTime;
        }
    }

    if(mTimeAttemptingToClimb >= sMaxTimeAttemptingToClimb)
    {
        mAttemptingToClimb = false;
        std::cout << "Give up" << std::endl;
    }

    mAcceleration = (mOrientation.getForward() * -forwardAccel) + (mOrientation.getRight() * rightAccel);

    //std::cout << "ACCEL " << mAcceleration.x << ", " << mAcceleration.y << ", " << mAcceleration.z << std::endl;

    if(!mAttached)
    {
        applyAcceleration(deltaTime);
        applyGravity(deltaTime);
        limitVelocity(deltaTime);
    }

    mOrientation.translate(mVelocity.x*deltaTime, mVelocity.y*deltaTime, mVelocity.z*deltaTime);

    //Re-orient camera and aim vector.
    mAzimuth += mDeltaAzi;// * deltaTime;
    mAltitude += mDeltaAlt;// * deltaTime;
    if(mAltitude > sMaxAltitude) mAltitude = sMaxAltitude;
    if(mAltitude < sMinAltitude) mAltitude = sMinAltitude;

    //Only change forward and right vectors.
    mOrientation.resetRotation();
    mOrientation.yaw(mAzimuth);

    //Never roll.
    mFPCamera->orientation()->resetRotation();
    mFPCamera->orientation()->pitch(mAltitude);

    //Aim vector is the same as camera forward.
    mAim = glm::rotate(mOrientation.getForward(), float(mAltitude), mOrientation.getRight());

    glm::vec3 forward = mFPCamera->orientation()->getForward();
    forward.x = -(forward.x);
    forward.z = -(forward.z);
    mCrosshairRay->setDirection(mFPCamera->orientation()->getForward() * -sLungeRange);
    //mCrosshairRay->setDirection(forward * sGrabRange);

    if(myWorldPos.y < sFallLimit)
    {
        mOrientation.setPos(mSpawnPos);
        mVelocity = glm::vec3(0.0f);
        mAcceleration = glm::vec3(0.0f);
    }

    mTransform = mOrientation.getOrientationMatrix();

    mIsGrounded = false;
    mCanMoveForward = true;
    mCanMoveBackward = true;
    mCanMoveLeft = true;
    mCanMoveRight = true;
    mCanJump = true;

}
Пример #10
0
int main() {

	Screen screen;
	
	long long previousTime = (long long)Util::getCurrentTimeInMiliseconds();
	long long accumulateTime = 0;
	Keyboard::startListening();
	
	Point f_pos(50,20);
	Color  f_col(255,255,255,255);
	Pixel f_plane(f_pos, f_col);
	propeller.setDrawPosition(145,30);
	
	bird.setPosition(50,20);
	fish.setPosition(50,20);

	roda1.setRadius(10);
	roda1.setCenter(Point(40,50));

	roda2.setRadius(10);
	roda2.setCenter(Point(120,50));
	parasut.setPosition(50,10);
	//plane.setPosition(200,10);
	//plane.fillColor(f_plane);
	//plane.fillPattern(&bird);
	
	ship.setPosition(10,250);
	
	
	
	f_pos.x = 50; f_pos.y = 20;
	Pixel f_ship(f_pos, f_col);
	//ship.fillColor(f_ship);
	
	f_pos.x = ship.getWidth() / 2;
	f_pos.y = ship.getHeight() / 2;
	
	
	ship.fillWithFloodFill(f_pos,&fish);
	

	int ii = 0;

	float speed = 0;
	float initialPercentage = 0;
	
	/* Game Clock */
	while (true) {
		if (accumulateTime>(SECONDS_PER_FRAME)) {
			handleInput();
			
			printf("%c[%d;%df",0x1B,199,99);
			screen.beginBatch();
			
			
			if (isPlane){
			  //planeEx += 0.05f;
			  //meledak.setPosition(meledak.getPosition().x - 2,meledak.getPosition().y - 2);

			
	
			    initialPercentage += 0.07;
			plane.explode(initialPercentage);
				speed += 0.1f;

			propeller.applyGravity((int)speed);

			applyGravity(&parasut,(int)speed);
			screen.draw(&parasut);

			if (!isPlaneGrounded){
				isPlaneGrounded = roda1.applyGravity((int)speed);
				roda2.applyGravity((int)speed);
			}else{
				propeller.setState(0);
				isBanSelesai = !roda1.bounce();
				roda2.bounce();
			}

			usleep(FRAMERATE/4);
			  //screen.draw(&meledak, planeEx);
			  
			  if (isBanSelesai){

			      //screen.beginBatch();
			      //screen.endBatch();

			  	  isPlane = false;
			      //isAftermath = true;

				//gotoxy(1, 10);
			      //printf("\t\tSHIP WIN!\n\n\n\n\n\n\n\n\n\n");
			      isFinish = true;

				  /* TODO:
			         - Animasi pesawat pecah
			         - Kasih Gravity tiap pecahan pesawat biar jatuh:
			           - baling-baling
			           - ban
			           - potongan badan pesawat
			           - pilot keluar dari pesawat pake parasut
			         - Bikin ban mantul-mantul di atas tanah -_-
			      */

			      // gotoxy(10, 10);
			      // printf("SHIP WIN!\n\n\n\n\n\n\n\n\n\n");

			      // exit(0);

			  }
			}

			screen.draw(&plane, isFlipPlane);
			screen.draw(&roda1);
			screen.draw(&roda2);
			

			propeller.draw(&screen);

			if (isShip){
			  shipEx += 0.05f;
			  
			  meledak.setPosition(meledak.getPosition().x - 2,meledak.getPosition().y - 2);
			  screen.draw(&meledak, shipEx);
			  
			  if (shipEx > 2){
			      screen.beginBatch();
			      screen.endBatch();
			      //gotoxy(10, 10);
			      //printf("PLANE WIN!\n\n\n\n\n\n\n\n\n\n");
			      isFinish = true;
			      isShip = false;
			  }
			}else if (!isPlane) screen.draw(&ship, isFlipShip);
			
			// handle peluru
			for (int i = 0; i < 100; i++){
				if (b[i] != NULL){
					Point st = b[i]->getPoint();
					bool arah = b[i]->arah;
					b[i] = bf.create(BulletFactory::LASER);
					
					if (arah == true){ //pesawat yang nembak, pelurunya kebawah
						b[i]->arah = true;
						b[i]->rotate(180);
						b[i]->setPoint(Point(st.x, st.y + 1));
						
						if (st.y > 330) b[i] = NULL;
						
						if (st.x > ship.getPosition().x  - 10 && st.x < ship.getPosition().x + 150 && st.y > 220){	// COLLISION
						    meledak.setPosition(ship.getPosition().x,ship.getPosition().y);
						    isShip = true;
						    b[i] = NULL;
						}
						
					}else{
						b[i]->arah = false;
						b[i]->setPoint(Point(st.x, st.y - 1));
						
						if (st.y < 0) b[i] = NULL;
						
						if (st.x > plane.getPosition().x - 5 && st.x < plane.getPosition().x + 180 && st.y < 40){	// COLLISION
						    meledak.setPosition(plane.getPosition().x,plane.getPosition().y);
						    isPlane = true;
						    b[i] = NULL;

							Point explosionCenter(plane.getWidth()/2,plane.getHeight()/2);

							//Ini harus dipanggil sebelum meledak
							plane.startExplode(explosionCenter);
						}
					}
					if (b[i] != NULL) screen.draw(b[i]);
				}
			}

			if (isAftermath) {
				
			//	speed += 1; // speed untuk gravity pull
			//	isPlaneGrounded = plane.applyGravity(speed); /* Kasih efek gravity, return valuenya bakal 1 kalo object nya udah sampe "tanah" */				
			//	screen.draw(&plane, isFlipPlane); /* Ini buat gambar objek2 yang udah mulai jatoh ke tanah */
			//	usleep(FRAMERATE); // ini buat ngedelay kecepetan refresh frame biar gak terlalu cepet
				initialPercentage += 0.01;
				plane.explode(initialPercentage);

				if(initialPercentage == 1) { // periksa kalo semua objek udah sampe tanah, berarti game nya pindah ke state finish
					isAftermath = false;
					isFinish = true;

					screen.beginBatch();
					screen.draw(&plane, isFlipPlane); // ini buat gambar object2 yang udah berserakan di tanah
					screen.endBatch();

					//gotoxy(10,10);
				//	printf("Ship Wins!\n\n\n\n\n");
				//	gotoxy(40,40);
				//	printf("\n");
				}
			}

			if (isFinish) {
				exit(0);
			}

			screen.endBatch();
			
			while (accumulateTime<(SECONDS_PER_FRAME))
				accumulateTime -= (SECONDS_PER_FRAME);
				
		}
		else {
			long long currentTime = (long long)Util::getCurrentTimeInMiliseconds();
			accumulateTime += (currentTime - previousTime);
			previousTime = currentTime;
		}
	}

	return 0;	
}
Пример #11
0
void joyHandler(u16 joy, u16 changed, u16 state) {
	switch (joy) {
		case JOY_1:
        if (state & BUTTON_A) {
				if (board[SEL(cursor.posy)][SEL(cursor.posx)].selected == TRUE) {
					int deleted_amount = recursiveDelete(SEL(cursor.posx),SEL(cursor.posy), board[SEL(cursor.posy)][SEL(cursor.posx)].id);
					if (deleted_amount == 1)
						score-=10;
					else
						score+=deleted_amount * 10;
					applyGravity();
					applyLeftShift();
					drawBoard();
					selected = FALSE;
				}
				else if (board[SEL(cursor.posy)][SEL(cursor.posx)].id != 0) {
					if(selected) {
						unselectEverything();
					} 
					selected = TRUE;
					recursiveFloodSelect(SEL(cursor.posx), SEL(cursor.posy), board[SEL(cursor.posy)][SEL(cursor.posx)].id, TRUE);
					drawBoard();
				} else {
					if(selected) {
						unselectEverything();
						selected = FALSE;
						drawBoard();
					}
				}
		}
		if (state & BUTTON_UP) {
			if (SEL(cursor.posy) > 0) {
				int oldy = cursor.posy;
				while(cursor.posy != oldy - 16) {
					VDP_waitVSync();
					cursor.posy-=CURSOR_INCREMENT_SPEED;
					VDP_setSpriteDirectP(0, &cursor);
				}
			}
		}
		if (state & BUTTON_DOWN) {
			if (SEL(cursor.posy) < BOARD_Y - 1) {
				int oldy = cursor.posy;
				while(cursor.posy != oldy + 16) {
					VDP_waitVSync();
					cursor.posy+=CURSOR_INCREMENT_SPEED;
					VDP_setSpriteDirectP(0, &cursor);
				}
			}
		}
		if (state & BUTTON_LEFT) {
			if (SEL(cursor.posx) > 0) {
				int oldx = cursor.posx;
				while(cursor.posx != oldx - 16) {
					VDP_waitVSync();
					cursor.posx-=CURSOR_INCREMENT_SPEED;
					VDP_setSpriteDirectP(0, &cursor);
				}
			}
		}
		if (state & BUTTON_RIGHT) {
			if (SEL(cursor.posx) < BOARD_X - 1) {
				int oldx = cursor.posx;
				while(cursor.posx != oldx + 16) {
					VDP_waitVSync();
					cursor.posx+=CURSOR_INCREMENT_SPEED;
					VDP_setSpriteDirectP(0, &cursor);
				}
			}
		}
		break;
	}
}