I’m trying to create a script that I can apply to a game object in which whenever the draggable object comes into contact with the target object, it will initiate ‘smooth follow’ and stay alongside the target object. I’ve attempted to get this to work to no avail. Any ideas?
I applied smooth follow and set the target to the object in question, but the problem is, all of these objects merge to center, creating unwanted effects.
What I really want is for the draggable object to come in contact with the other draggable object (the target object) and remain in the position it was in once it intersected with the target object, and follow along the target object when the target object is dragged elsewhere.
import { Behaviour, Collision } from "@needle-tools/engine";
import { DragControls } from "@needle-tools/engine"; // Import the DragControls class
export class FollowRedSphere extends Behaviour {
private redSphere: any = null; // Reference to the red sphere
private offset: THREE.Vector3 | null = null; // Offset between the object and the red sphere
onCollisionEnter(col: Collision) {
// Check if the collided object's name is "RedSphere" and if the object is not already connected
if (col.gameObject.name === "RedSphere" && this.offset === null) {
// Log the collision event, including the name of the object that collided
console.log(`Object "${this.gameObject.name}" collided with the red sphere.`);
// Get the DragControls component and disable it
const dragControls = this.gameObject.getComponent(DragControls);
if (dragControls) {
dragControls.enabled = false;
}
// Store a reference to the red sphere
this.redSphere = col.gameObject;
// Calculate and store the offset between the object and the red sphere
this.offset = this.gameObject.position.clone().sub(this.redSphere.position);
}
}
update() {
// If connected to the red sphere, update the position to follow the red sphere
if (this.offset && this.redSphere) {
// Calculate the new position based on the red sphere's position and the stored offset
const newPosition = this.redSphere.position.clone().add(this.offset);
// Set the new position
this.gameObject.position.copy(newPosition);
}
}
}