Attaching and activating MouseJoint2D on Ridged Bodies under the mouse

Hello Cocos Community! I am loving CocosCreator and got a lot done.

I attached the MouseJoint2D to a ridged body I want to interact with and it works pretty well.

My issue is, for my game, I need the mouse to find what is under it and then add the mousejoint2d to the ridged body.

I have made code that uses raycasts to find what has been “hit” and apply tje mousejoint2d to it. But its not… “active”? Its enabled, but it seemes the mousejoint2d is Demanding I click on the object first, I want it so I can click somewhere outside of the object, but if i move my mouse over the object, auto apply the mousejoint and have it in the “draging” state.

I tested this with the in-app preview and I can see my mousejoint getting created and even tried to set the connectedbody manually but it seems to not enter the “dragging” state.

Because its so easy to add a mousejoint, I feel there must be some way to get it to enter the dragging or clicked state without doing the actual click.

Thanks in advance, im still quite new so hoping there is a helper function or something to fix this.

So using target doesn’t seem to work. Looking at the engine code it seems mouseJoint needs to be clicked on before it will accept mouse/touch positions.


canvas.on(NodeEventType.TOUCH_START, this.onTouchBegan, this);

/cocos/physics-2d/box2d/joints/mouse-joint.ts#L80C7-L80C7

I tried spoofing a mouse event on it but doesn’t seem to work. is there another way to force… “Focus” or pass in the correct mouse event when setting a Joint target via code?

So after hunting for a solution, I went to the Chinese forums and found that some people suggest that mouseJoint is more of a debug tool. So I decided to attach my own joint to it dynamically in code but for some reason I can not attach a connected body.

I found on the Chinese forums that joints are missing an apply function to tell box2d to re-calculate joints and will be in the next version 3.8.2.

github
cocos/cocos-engine/pull/16299

current version at time of writing is 3.8.1

Oh and for my solution. I decided to drop attaching a fixed joint dynamically and just attached a fixed joint to all my assets and connected it to a “mouseAnchor” and all I do is change the anchor position and enable/disable the joint on demand. This works quite well, wish the mouse joint could be told to listen to all touch events and apply it’s logic if a ridged body falls under the pointer at anytime rather than demand the explicit action of touching the node directly.

So anyone who needs this. As of 3.8.2, you can now manually call the .apply() function to force box2D to recalculate joints. An issue I found is that the dampening, max strength and restitution values seem to get extremely weak by a factor of 10 after using the .apply function. Gonna try to get a video to demo this.