The aim of this puzzle: Make the player
hop to the right when the yellowButton
is tapped.
Walkthrough of the solution: The hopping animation has 2 .transition()
s: 1st move the player
to the side and lift it up, 2nd drop the player
down and let it bounce.
The blueButton
's .on('click',)
is already complete. The 1st .transition()
has .attr('cx',playerCX).attr('cy',100)
. That will move the circle to the left by using the updated playerCX
value and up to 100. The yellowButton
should also have an .attr('cy',100)
so that the player
goes up as it moves to the side.
The 2nd .transition()
for the blueButton
moves the 'cy'
back to to ground which is stored in playerCY
. To make the circle bounce, the .ease()
of the .transition()
has to be changed. D3 has an easing function called easeBounce
which can be accessed using d3.easeBounce
. Inside the yellowButton
's arrow function, attach another .transition()
followed by the .attr('cy',playerCY)
and then .ease(d3.easeBounce)
. The order of the last .attr()
and .ease()
can be swapped, as long as they both come after the 2nd .transition()
.
Sample code solution:
(Tap below to reveal)
blueButton.on('click', () => {
playerCX -= 30;
player.transition()
.attr('cx', playerCX)
.attr('cy', 100)
.transition()
.ease(d3.easeBounce)
.attr('cy', playerCY);
});
yellowButton.on('click', () => {
playerCX += 30;
player.transition()
.attr('cx', playerCX)
.attr('cy', 100)
.transition()
.ease(d3.easeBounce)
.attr('cy', playerCY);
});
JavaScript Concepts: Assignment Operator (+=
, -=
),Code Block (arrow function), Member Expression, Identifiers
D3 Concepts: .attr('cx',)
, .attr('cy',)
, .ease()
, .on('click',)
, .transition()
Additional Code (hidden code that runs before the puzzle’s code):
let color = [...Array(36)].map((_,i)=>`hsl(${10*i},100%,50%)`);
let playerCX = window.innerWidth/2;
let playerCY = window.innerHeight-30;
let player = svg.append('circle').attr('r',30).attr('cx',playerCX).attr('cy',playerCY).attr('fill',pickRandom(color));
let blueButton = svg.append('rect').attr('width',50).attr('height',50).attr('x',0).attr('y',0).attr('fill','#4285F4');
let yellowButton = svg.append('rect').attr('width',50).attr('height',50).attr('x',50).attr('y',0).attr('fill','#F4B400');