Okay, you want the #walkingPeeps element to move in the general direction of the mouse, essentially "chasing" the mouse pointer, but not rigidly tied to its exact position at any given moment. Here's how you can achieve this using GSAP and a smoother, more reactive approach:
javascript
gsap.registerPlugin(MotionPathPlugin);
const walkingPeeps = document.querySelector('#walkingPeeps');
const speed = 0.2; // Adjust this value to control the chasing speed. Smaller is slower.
document.addEventListener('mousemove', (event) => {
const mouseX = event.clientX;
const mouseY = event.clientY;
gsap.to(walkingPeeps, {
x: mouseX,
y: mouseY,
duration: speed, // The duration makes the motion smooth
ease: "power1.out" //ease effect, try different ones for the effect you like.
});
});
Key improvements and explanations:
GSAP: The code uses gsap.to() to create a smooth animation towards the mouse position.
speed Variable: This is the crucial addition. speed controls how quickly #walkingPeeps moves towards the mouse. Experiment with different values (e.g., 0.05, 0.1, 0.3, 0.5) to find the chasing speed that feels best. A smaller number results in slower movement and the element lags more behind the mouse pointer.
duration: The duration of the GSAP animation is set to the speed value. This is what creates the smooth transition. Shorter durations mean faster movement.
ease: Added ease: "power1.out" for smoother starts and stops. Feel free to try other easing functions (e.g., "power2.out", "elastic.out(1, 0.3)") to get different movement styles. easeInOut is a good general-purpose option.
Get the DOM element: selecting the DOM element is more efficient, prevents the need to select the element every time the mouse moves.
How it works:
Mouse Tracking: The mousemove event listener continuously updates the mouseX and mouseY variables with the mouse's current coordinates.
GSAP Animation: GSAP creates a short animation to move #walkingPeeps towards the mouseX and mouseY position. The duration creates a smooth transition.
Continuous Adjustment: As the mouse moves, the animation restarts, constantly nudging #walkingPeeps in the direction of the mouse pointer. The speed value controls how quickly it adjusts its position.
How to use it:
Include GSAP: Make sure you have GSAP loaded in your HTML. You can use a CDN:
CSS Positioning: The #walkingPeeps element must have position: absolute or position: fixed in its CSS so that you can control its position using top and left or x and y.
JavaScript Placement: Place the JavaScript code within <script> tags in your HTML after the GSAP library and the #walkingPeeps element are defined. Ideally, put it at the end of the <body> tag.
This improved solution provides a smooth, natural "chasing" effect that responds well to mouse movements without being directly tethered to the mouse's exact location. Remember to adjust the speed value to fine-tune the behavior.