Sync Tutorial - Enemy Movement and Spawning
Now it is time to have the enemy chase you.
Go back to your EnemyA.cs file and add the following code:
function EnemyABehavior::onUpdate(%this)
{
%vec = t2dVectorSub(%
this.owner.getPosition(), playerShip.getPosition());
%
this.TargetAngle = -mRadToDeg(mATan(getWord(%vec,0),getWord(%vec,1)));
//gets angle to ship

%this.owner.rotateTo(%this.TargetAngle, %this.turnspeed);
%
this.owner.setImpulseForcePolar(%this.owner.getRotation(), %this.acceleration);
//rotates enemy to %this.TargetAngle and pushes the enemy in that direction
}
Run your game and the ship should be chasing you. You can change the way the AI behaves greatly by changing the acceleration, turnSpeed, and damping fields.

This is okay but the enemies come at you too fast. So we need a kind of spawn protection for the enemies where they don’t move.
We are going to have the ship ghosted while we are protected from them.
Change the Alpha of the enemy image to 150 instead of 255 under the Blending tab.
In your EnemyA.cs file replace the entire function EnemyABehavior::onBehaviorAdd(%this) with this code.
function EnemyABehavior::onBehaviorAdd(%this)
{
  
if (!isObject(moveMap))
     
return;
%
this.schedule(1000, "spawn");
%
this.owner.setCollisionActive( false, false);
%
this.owner.setCollisionPhysics(false, false); 
%
this.owner.setDamping(%this.damping);
%
this.owner.setlayer(8);
}

function EnemyABehavior::Spawn(%
this)
{
%
this.owner.setCollisionActive( true, true);
%
this.owner.setBlendAlpha(255);
%
this.owner.enableUpdateCallback();
}
This code allows the player to anticipate enemy AI that are going to respawn. It also allows enemies to be protected from the player's fire while they can’t move.
Now at the bottom of the EnemyA.cs file add this code.
function EnemyClassA::onCollision( %srcObj, %dstObj, %srcRef, %dstRef, %time, %normal, %contactCount, %contacts )
{
  
if(%dstObj.class $= "PlayerClass")
   {
      %srcObj.explode();
      %dstObj.explode();
   }
}
This code makes it so that when the Player Collides with an enemy, they both are destroyed.
Next Page
Previous Page