Hello,
i’m trying to put an object in an AR environment and to move by drag my finger. I saw that I had to use a raycast and screenToWorld but I am new to programming and not sure to completely understand how to do it. When I drag the object it disappear while I am dragging. My code is in the EntityPositioner script :
https://playcanvas.com/editor/scene/2142948
if (this._inputSources.length === 1 && this._isDrag) {
const inputSource = this._inputSources[0];
const screenPos = inputSource.getOrigin(); // Assuming getOrigin provides 2D screen coordinates
// Perform raycasting to find intersection with a flat plane (ground)
const ray = new pc.Ray();
const hitPosition = new pc.Vec3();
const groundPlane = new pc.Plane(); // Define a flat horizontal plane
// Set the plane's normal and point (assuming it's horizontal at Y = 0)
groundPlane.normal.set(0, 1, 0); // Horizontal plane normal
groundPlane.d = 0; // Distance from origin
this.arCamera.camera.screenToWorld(
screenPos.x,
screenPos.y,
this.arCamera.camera.nearClip,
ray.origin
);
this.arCamera.camera.screenToWorld(
screenPos.x,
screenPos.y,
this.arCamera.camera.farClip,
ray.direction
);
ray.direction.sub(ray.origin).normalize(); // Normalize direction
// Check ray-plane intersection
const distance = ray.intersectsPlane(groundPlane);
if (distance !== null && distance > 0) {
ray.getPoint(distance, hitPosition); // Get the intersection point on the plane
// Adjust the target entity position
const targetPosition = new pc.Vec3(hitPosition.x, this.targetEntity.getPosition().y, hitPosition.z);
this.targetEntity.setLocalPosition(targetPosition);
}
}