# Pixi Particle Attraction/Repulsion to Mouse Help

## Recommended Posts

Hi so i cant seem to figure out how to calculate the mouse position relative to randomly created sprites in a particle container so I can create a attraction or repulsion effect when the mouse cursor gets close to the particle. If someone could help that would be greatly appreciated. The general method im trying to implement but not working is below.

creating random x/y cords with this function:

function rand(min, max) {
if (max == null) {
max = min;
min = 0;
}
if (min > max) {
var tmp = min;
min = max;
max = tmp;
}
return min + (max - min) * Math.random();
}

Then trying to create the sprites and calc the mouse coordinates/sprite coordintaes:

stars = [];
for (var i = 0; i < totalStars; i++) {

var star = new Sprite(id["star.png"]);
star.interactive = true// enable mouse and touch events
star.buttonMode = true// show hand cursor on mouseover

star.scale.set(rand(0.05.07));
star.anchor.set(.5);
star.=  rand(vWidth / 2, vWidth / -2);
star.= rand(vHeight / 2, vHeight / -2);
stars.push(star);

function calculateStarPosition(){
// mouse coordinates
let mouseCoords = app.renderer.plugins.interaction.mouse.global;

let starCenterPosition = new PIXI.Point(
star.+ (star.width * 0.5),
star.+ (star.height * 0.5),
);
let toMouseDirection = new PIXI.Point(
mouseCoords.- starCenterPosition.x,
mouseCoords.- starCenterPosition.y,
);
let distance = distanceBetweenTwoPoints(mouseCoords, star.position)

// Use the above to figure out the angle that direction has
const angleToMouse = Math.atan2(
toMouseDirection.y,
toMouseDirection.x,
);
/*    var starpos = { left: star.x, top: star.y }; */

// TweenMax.to(sign, 0.3, {scale: 2});
gsap.to(star, {pixi:{scale: "+=.1"}, duration:0.3,});
} else{
// TweenMax.to(sign, 0.3, {scale: 1});
gsap.to(star, {pixi:{scale: .1}, duration:0.3});
}
gsap.to(star, {pixi:{
}});
}
}

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.