DEV Community

Cover image for Experimenting with Three.js: Devlog #2
Andriy Chemerynskiy
Andriy Chemerynskiy

Posted on • Updated on

Experimenting with Three.js: Devlog #2

Before you read it

This is not a tutorial and I am not a Three.js expert. I am going to document my learning journey and share it with you. If you find it useful then I would appreciate you leaving a comment or liking this post. Thanks and let's get started 😎


Controls and wall collision problem

In the previous devlog, I added PointerLockControls to my scene and assign movement on keypress (W, A, S, D keys). And as mentioned there is a problem that camera can pass throw walls.

I didn't work with game dev or 3D before, so it was difficult for me to think about a solution for this.

My initial thought was to create enough if statements that would prevent the camera from passing throw walls (it was a super dummy idea πŸ˜…).

After struggling with it for some time, I discovered that there is a much easier and better solution for this.

Introducing physics

I found this wonderful answer to my problem on Stackoverflow:

Stackoverflow answer

It sounds way better than adding an infinite number of if statements πŸ€”

In easier words, it means that the viewer is a ball and if it will collide with the wall then physics will do its job 😱

As Einstein once said:
Einstein quote

(or something like that).

Using use-cannon

There is a great library for handling physics use-cannon.

I defined walls using useBox hook and sphere using useSphere. Here is the result:

useSphere and useBox example

For debug purposes, I used Debug component

Applying camera to the sphere

The last and most challenging part is to add the camera to the sphere.

I was lucky to find this tutorial: https://www.youtube.com/watch?v=ZnXKmODEFHA

I won't write in detail how it is done, because you can check it on your now πŸ˜‰ But basically it just subscribing to sphere/ball position and setting the camera to that place.

Wall collision use-cannon

And it is done πŸŽ‰

Here is how it looks all together:

Wall collision threejs

It looks like something basic on this video, but it felt soooo good to hit that wall and be stoped by the laws of physics 😍


You might think that we are finished with controls and can move on to more advanced stuff. Not really...

PointerLockControls won't work on mobile and we need to find another way of doing it. But I would talk about it in the next devlog πŸ˜‰

Thanks for reading! πŸ™Œ

Top comments (1)

Collapse
 
mulualemtekle profile image
Mulualem Tekle

have you found a way to make things work on mobile?