Its been a long time

Hello Chris, how are you.
Anyway,
I was wondering if you can make if my avatar touches the key(The yellow sphere) the key dissapears.

Cheers,
Martin:)

Hi Martin!

Welcome back! I’m well, hope all is well with you too. I am not sure that I quite follow your question. Can you post your code? If you can do that, I’ll have a look as see if I can figure out what is going on.

Thanks!

-Chris

1 Like

No, i mean that I need the collision script if the avatar is colliding with a key(the yellow sphere ) the key just dissapears and it looks like it was picked up.

There are a couple of approaches here. Either way, you’ll want to add an isCollidingWithKey() inside the sendKeyDown() function. It will look something like:

function sendKeyDown(event) {
   // The rest of your code here...
  if (isCollidingWithKey()) pickUpKey();
}

The pickUpKey() function can be something simple like:

function pickUpKey() {
  scene.remove(key);
}

At some point, you can improve this by adding animation or scoring, but the above should get you started.

As for the isCollidingWithKey() function, you can start with something like:

function isCollidingWithKey() {
  var xDiff = marker.position.x - key.position.x;
  var zDiff = marker.position.z - key.position.z;
  var distance = Math.sqrt(xDiff**2 + zDiff**2);
  return distance < 50;
}

This function uses the Pythagorean theorem to determine the distance between the key and the avatar’s marker. If the distance is less than 50 (which is the size of the key), then this function will return true, causing pickupKey() to be called. If the distance is 50 or greater, then this function will return false.

The other approach that you can take with isCollidingWithKey() is similar to the raycaster approach that we use in this chapter for determining how close we are to the trees.

Hope that helps!

-Chris

Oh yes! It works but i get an Warning under Here:
function isCollidingWithKey() {
var xDiff = marker.position.x - key.position.x;
var zDiff = marker.position.z - key.position.z;
var distance = Math.sqrt(xDiff2 + zDiff2);
return distance < 50;
}

That Line of Code gets me a Warning idk what’s happening. var distance = Math.sqrt(xDiff2 + zDiff2);

That line is supposed to be x-squared plus z-squared:

  var distance = Math.sqrt(xDiff**2 + zDiff**2);

You could also write this as:

  var distance = Math.sqrt(xDiff*xDiff + zDiff*zDiff);

-Chris