Skip to content

Instantly share code, notes, and snippets.

@Gi972
Last active February 16, 2020 01:11
Show Gist options
  • Select an option

  • Save Gi972/8e2e89b10200d41bc639403c5f9e3a46 to your computer and use it in GitHub Desktop.

Select an option

Save Gi972/8e2e89b10200d41bc639403c5f9e3a46 to your computer and use it in GitHub Desktop.
SCRIPT-8
function world(item){
const {x,y,width} = item;
let touchleft = x<0;
let touchright = (x>(128-width))
return {touchleft , touchright}
}
const a =()=> { left=false };
init = state => {
state.ball = ball().init()
state.player = player().create()
}
update = (state, input, elapsed) => {
let{ left, right,up, down , start} = input
state.ball = ball(state.ball).move(start)
world(state.player).touchleft && (left=false)
world(state.player).touchright && (right=false)
const whenCollide = ()=>{
state.player.color = 5
state.ball.speedX = -state.ball.speedX
state.ball.speedY = -state.ball.speedY
}
const whenNoCollide = ()=>{
state.player.color = 0
}
ball(state.ball).collide(state.player)
? (whenCollide())
: (whenNoCollide())
state.player = player(state.player).move(left,right)
}
draw = state => {
clear();
ball(state.ball).display()
player(state.player).display()
}
function ball(ball){
const init = function init(){
return {x:56,y:54, radius:2, speedX:0, speedY:0, width:2, height:2};
}
const move = function move(start){
let {x,y,speedX, speedY,...rest } = ball
if(start){
speedX = clamp(random(-1, 1), -1, 1)
speedY = -1
}
speedX = (x < 0 || x > 128 ) ? -speedX : speedX;
speedY = (y < 0 || y > 128 ) ? -speedY : speedY;
x=x+speedX
y=y+speedY
return {x,y,speedX, speedY, ...rest};
}
const collide = function collide(boxb){
const {x:ax ,y:ay, height:aheight, width:awidth } = ball;
const {x:bx, y:by, height:bheight, width :bwidth } = boxb;
const touchup = ()=> ay+aheight > by
const touchdown = ()=> ay+aheight < by + bheight
const touchleft =()=> ax+awidth > bx
const touchright = ()=> ax+awidth < bx +bwidth
return touchup()
&& touchdown()
&& touchleft()
&& touchright()
}
const display=()=>{
circFill(ball.x, ball.y, ball.radius)
}
return {init, move, collide, display}
}
function player(player){
const create = function create(){
return {x:54,y:100, width:20,height:5, color:0 };
}
const move = (left,right)=>{
let{ x,y, speed,width, ...rest } = player;
const increase=speed =>{
x = x+speed
}
left && increase(-1)
right && increase(1)
return { x,y, speed,width, ...rest}
}
const display=()=>{
rectFill(player.x, player.y,player.width,player.height,player.color)
}
return {create, move, display}
}
{
"iframeVersion": "0.1.280",
"lines": [
43,
50,
26,
0,
0,
0,
0,
0
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment