trendstar93 Posted May 30, 2020 Share Posted May 30, 2020 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.x = rand(vWidth / 2, vWidth / -2); star.y = rand(vHeight / 2, vHeight / -2); stars.push(star); spriteParticles.addChild(star); function calculateStarPosition(){ // mouse coordinates let mouseCoords = app.renderer.plugins.interaction.mouse.global; let starCenterPosition = new PIXI.Point( star.x + (star.width * 0.5), star.y + (star.height * 0.5), ); let toMouseDirection = new PIXI.Point( mouseCoords.x - starCenterPosition.x, mouseCoords.y - 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 }; */ var radius = 5; if(distance < radius){ radius = distance; // 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:{ x: Math.cos(angleToMouse) * radius, y: Math.sin(angleToMouse) * radius }}); } } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.