Bot
In this part of the tutorial we will make the botPaddle.
Setup
- Copy the userPaddle and rename it to botPaddle.
- Move the botPaddle to [0,0,-15.5]
- Change the color of the bot paddle to red
Logic
We will update the movement.ts script to handle bot logic.
- To distinguish between the bot and the user, add a key
auto
to the props of the movement.ts file.
TypeScript
export const props = {
speed: 5, // speed of movement
auto: false, // automatic (true if this is the bot paddle)
};
Tick the checkbox for
auto
in the component editor for botPaddle.Update the movement.ts file to add the logic for the bot. Here we are assuming in advance that there will be a child of the rootGameObject called
puck
. We will try to get this objects position and then update the botPaddle's position bsed on this.
TypeScript
export const props = {
speed: 1,//speed of movement
auto: false,//automatic
};
export const init = (game, gameObject, {props}) => {
let horizontal = 0;
let vertical = 0;
if(!props.speed)props.speed = 1;//use default speed if speed was not changed
const updateLinVel = () => {//update linear velocity
const rb = gameObject.components.rigidBody;
if(!rb)return;
rb.setLinvel({ x: horizontal* props.speed, y: vertical*props.speed, z: 0 }, true);
};
if(props.auto){// if this is the bot then set the speed automatically
setInterval(() => {
//get the puck rigidBody
const puckRb = game.currentGameObject?.children?.puck?.components?.rigidBody;
//get self rigidBody
const selfRb = gameObject.components.rigidBody;
//if any of the above is not initialized yet, return.
if(!puckRb || !selfRb)return;
//get the difference in positions and calculate the linear velocity
const puckPos = puckRb.translation();
const selfPos = selfRb.translation();
horizontal = Math.sign(puckPos.x - selfPos.x);
vertical = Math.sign(puckPos.y - selfPos.y);
updateLinVel();
}, 16);
}else{// allow manuall control
window.addEventListener('keydown', e => {
if (e.repeat) { return }
switch(e.code){
case 'KeyA':
horizontal -= 1;
break;
case 'KeyD':
horizontal += 1;
break;
case 'KeyS':
vertical -= 1;
break;
case 'KeyW':
vertical += 1;
break;
};
updateLinVel();
})
window.addEventListener('keyup', e => {
switch(e.code){
case 'KeyA':
horizontal += 1;
break;
case 'KeyD':
horizontal -= 1;
break;
case 'KeyS':
vertical += 1;
break;
case 'KeyW':
vertical -= 1;
break;
};
updateLinVel();
});
}
}
- At this point there should be no visible difference in the game because there is no gameObject named
puck
inside the rootGameObject. - Rename the
cube
topuck
and you should see the botPaddle follow thepuck
falling down.