Add new objects by mouse clicking

Suppose I try to simulate traffic, where there are many vehicles running on the road network.

How could I let users add new vehicles by clicking the mouse?

For example, if I move mouse to a specific road line, what should I do to add vehicles on the specific road?

I think the first step is to find the correpoinding road line by mouse position. Could I use the CollisionNode(‘mouseRay’) to find the correponding road?

After I find the correpoinding road line, I could spawn a car on this road.

Thanks

Indeed, that would make sense I think.

This depends somewhat on your game, and how you’ve designed things thus far, but in general such an approach should work, yes. In fact, it’s likely to be one of my first suggestions!

Something that might be useful: If your roads are perfectly flat–that is, with no rises or drops at all–then Panda has a neat feature in its “plane” class that can aid in quickly and fairly-easily finding a point on such a plane (e.g. flat ground) that is indicated by the mouse. See this thread for more.

Exactly!

Quite how this is done again depends somewhat on your game. For example, if you have a custom “Car” class, then you might instantiate one of those, and set its position and direction in whatever means you’ve defined in the class.

Thank you so much for your reply!

We have succesfully get the correpoinding road line by using the CollisionNode.

I think the only problem is finding the physical world coordinate by the mouse and then we could add the vehicle to that position.
But the engine uses BulletShape to create the ground. For example, shape = BulletPlaneShape(Vec3(0,0,1), 0).

We have tried to find the mouse position by using getMouse function. But how to convert mouse position to the physical world position? Is there any function to do that?

1 Like

Ah, okay–I see two potential options, depending on your circumstances:

Again, if your world is perfectly flat and horizontal, then you could find the vector corresponding to your mouse-position (there are methods for that), feed it the height of your “ground”, and from that derive your world-position.

However, if your ground is not perfectly flat–or if you simply prefer this approach–then given that you’re using Bullet you might perform a “ray test”. In short, this has Bullet fire a “ray” along a given vector and report back on what it hits–and where.

See this manual page for more–and indeed, it even has examples showing how one might detect an object being clicked on, and the position of the click!

Sort of. The position of the mouse corresponds not to a point in the world, but to a line–after all, any point in space that lies under the mouse, however far “into the scene”, would correspond to the same mouse-position.