9.7 4 Leash Codehs Answers

9.7.4 Leash: CodeHS Answers

In this CodeHS exercise, students are tasked with creating a leash that will follow a ball. The leash should be attached to the ball’s center and should always be the same length.

Solution

The following code will solve this exercise:

function drawLeash(ball) { const center = ball.getCenter(); const end = { x: center.x, y: center.y - 100, }; drawLine(center, end); } 

This code first gets the ball’s center using the getCenter() method. Then, it creates a new point for the leash’s end that is 100 pixels below the ball’s center. Finally, it draws a line from the ball’s center to the end point using the drawLine() method.

Questions

  • How can you make the leash follow the ball more smoothly?

To make the leash follow the ball more smoothly, you can use the update() method to update the leash’s end point every frame. The following code shows how to do this:

function drawLeash(ball) { const center = ball.getCenter(); const end = { x: center.x, y: center.y - 100, }; function update() { end.y = center.y - 100; } drawLine(center, end); window.addEventListener("keydown", update); } 

This code uses the window.addEventListener() method to listen for the keydown event. When the keydown event occurs, the update() function is called. The update() function then updates the leash’s end point to be 100 pixels below the ball’s center.

  • How can you make the leash stretch and shrink?

To make the leash stretch and shrink, you can use the length property of the leash’s end point. The following code shows how to do this:

function drawLeash(ball) { const center = ball.getCenter(); const end = { x: center.x, y: center.y - 100, }; function update() { end.length = ball.radius; } drawLine(center, end); window.addEventListener("keydown", update); } 

This code uses the length property to set the leash’s length to be equal to the ball’s radius.

  • How can you make the leash change color?

To make the leash change color, you can use the fillStyle property of the drawLine() method. The following code shows how to do this:

function drawLeash(ball) { const center = ball.getCenter(); const end = { x: center.x, y: center.y - 100, }; function update() { fillStyle = ball.color; } drawLine(center, end, fillStyle); window.addEventListener("keydown", update); } 

This code uses the fillStyle property to set the leash’s color to be equal to the ball’s color.

These are just a few examples of how you can customize the leash in this CodeHS exercise.

Check Also

Apa arti dan makna dari kata Bravo?

Kata “bravo” adalah sebuah kata yang berasal dari bahasa Italia yang berarti “bagus” atau “hebat”. …

Leave a Reply

Your email address will not be published. Required fields are marked *