Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // snake
- var snake = {
- // the positions of all the parts
- positions: [],
- // the radius of the snake
- radius: 1,
- // the color of the snake
- color: '#ffff00',
- // inits the snake
- init: function() {
- this.positions.push({
- x: canvas.width / 2,
- y: canvas.height / 2
- });
- for (let i = 1; i < 200; i++) {
- this.positions.push({
- x: canvas.width / 2,
- y: canvas.height / 2 + 2 * i * this.radius
- });
- }
- },
- // renders the snake
- render: function() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.fillStyle = this.color;
- for (let i = 0; i < this.positions.length; i++) {
- ctx.beginPath();
- ctx.arc(
- this.positions[i].x,
- this.positions[i].y,
- this.radius,
- 0, 2 * Math.PI
- );
- ctx.closePath();
- ctx.fill();
- }
- },
- // moves the snake to a new point
- moveTo: function(x, y) {
- // positions[0] is the head of the snake
- this.positions[0].x = x;
- this.positions[0].y = y;
- this.join();
- },
- join: function() {
- // loop through each position
- for (let i = 1; i < this.positions.length; i++) {
- // get last and current position
- var last = this.positions[i - 1];
- var curr = this.positions[i];
- // get difference in x and y of each position
- var dx = curr.x - last.x;
- var dy = curr.y - last.y;
- // calculate the angle between the two parts of the snake
- var angle = Math.atan2(dy, dx);
- // get the new x and new y using polar coordinates
- var nx = 2 * this.radius * Math.cos(angle);
- var ny = 2 * this.radius * Math.sin(angle);
- // add the new x and new y to the last snake's position to "join" the two
- //together without a gap
- curr.x = nx + last.x;
- curr.y = ny + last.y;
- }
- },
- // slithers the snake smoothly to a new point
- slither (x, y) {
- var head = snake.positions[0];
- // smooth movement
- var nx = head.x + (x - head.x)/10 ;
- var ny = head.y + (y - head.y) /10;
- this.moveTo(nx, ny);
- }
- };
- // inits the snake
- snake.init();
- var mouse = false;
- window.addEventListener('mousemove', function(e) {
- mouse = {
- x: e.clientX,
- y: e.clientY
- };
- });
- window.requestAnimationFrame(function loop() {
- window.requestAnimationFrame(loop);
- // slithers the snake to a new point
- if (mouse) {
- snake.slither(mouse.x, mouse.y);
- }
- // renders the snake
- snake.render();
Add Comment
Please, Sign In to add comment