Rotation based on Mouse

(What I am asking is at the bottom, these are the assets I am expecting you will need.) I am currently working on a .io game project. Here is my code for the player:

function Snipe(img, x, y) {
    this.pos = createVector(x, y);
    this.img = img;
    this.vel = createVector(0,0);
    this.angle = 0;
    this.name = "I";
    this.score = 0;

    this.update = function() {
      var newvel = createVector(mouseX-width/2, mouseY-height/2);
      newvel.setMag(3);
      this.vel.lerp(newvel, 0.2);
      this.pos.add(this.vel);
    }
  
    this.show = function() {
      image(this.img, this.pos.x - 75, this.pos.y - 15);
      fill(255);
      textSize(20);
      textAlign(CENTER);
      text(this.name, snipe.pos.x, snipe.pos.y + 135);
    }
}

The player looks like this (I recommend putting a black background over it):
default

So, let’s get to the point. I am trying to make the player turn torwards the mouse. Not adding the ability to move torwards the mouse, I already got that, only just need to add the ability to rotate torwards the mouse. If you need more clarification, or more of my code (that was one, and I have 2), ask me. I was looking for this all over Google for one day, and no working results. Make sure it is pointing the mouse at the pointed end, rather than the rounded end. (You don’t have to, just try if it is possible.) Can you tell me how that is possible? Thanks! :wink:

Hi Sapphire,

atan2 is the key to making one object look at another in 2D.

'use strict';

let targetAngle = 0.0;
let currentAngle = 0.0;
let x = 0.0;
let y = 0.0;
let smoothSpeed = 0.02;
let scl = 25.0;
const count = 3;
let iToTheta;

function setup() {
	createCanvas(400, 400);
	x = width * 0.5;
	y = height * 0.5;
	iToTheta = TWO_PI / count;
}

function draw() {
	targetAngle = atan2(mouseY - y, mouseX - x);
	currentAngle = lerpAngle(currentAngle, targetAngle, smoothSpeed);
	
	background(220);
	
	noStroke();
	beginShape();
	for (let i = 0; i < count; ++i) {
		const theta = currentAngle + i * iToTheta;
		vertex(x + cos(theta) * scl, y + sin(theta) * scl);
	}
	endShape(CLOSE);
	
	strokeWeight(1.25);
	stroke(color(255, 0, 0));
	line(x, y, x + cos(targetAngle) * scl,
		y + sin(targetAngle) * scl);

	stroke(color(0, 255, 0));
	line(x, y, x + cos(currentAngle) * scl,
		y + sin(currentAngle) * scl);
}

// Linear interpolation of an angle.
function lerpAngle(a, b, step) {
	// Prefer shortest distance,
	const delta = b - a;
	if (delta == 0.0) {
		return a;
	} else if (delta < -PI) {
		b += TWO_PI;
	} else if (delta > PI) {
		a += TWO_PI;
	}
	return (1.0 - step) * a + step * b;
}

To incorporate this into the code in your show function, look at push, translate, rotate and pop. imageMode may also be helpful to control the pivot point of the image. A more in-depth example on rotation is here.

1 Like