Today, let's talk about the use of the Creator physics engine, and teach you to learn the physics engine in three steps.
Step 1: Start the physics engine
(1): Write a js component script and implement the following code in the onload function
properties: {
is_debug: false, // Whether to display debug information;
// The gravitational acceleration is a vector, directional, 2D, the magnitude of the Vec gravitational acceleration;
gravity: cc.p(0, -320), // system default
},
onLoad() {
cc.director.getPhysicsManager().enabled = true; // enable the physics engine
if (this.is_debug) { // enable debug information
var Bits = cc.PhysicsManager.DrawBits;
cc.director.getPhysicsManager().debugDrawFlags = Bits.e_jointBit | Bits.e_shapeBit;
}
else { // turn off debug info
cc.director.getPhysicsManager().debugDrawFlags = 0;
}
// Configuration of gravitational acceleration
cc.director.getPhysicsManager().gravity = this.gravity;
},
Note that you must write the code into the onLoad function, start the physics engine, configure the debugging area, and set the gravity of the object, not in start;
Step 2: Configure the object type of the game world:
Configure the object type and collision matrix of the game according to the situation of the game, as shown in the figure:
Step 3: Configure the physics object:
- Add a rigid body component to the section, as shown in the figure:
(2) Add a physical shape to the node: as shown in the figure;
Step 4: Collision Detection:
That node needs to detect collision, just hang a script on this node, and implement three functions on this script:
onBeginContact(contact, self, other): collision starts
onEndContact(contact, self, othe): end of collision
… …
contact: Get the collision information object, the own collider component instance where self collided, the other's collider component instance when other collided,
Through the collider component instance, you can get the node, the collided node other.node, etc.
Have you learned the basic use of the physics engine?