How to use a game controller in CocosCreator

How to use a game controller in CocosCreator

1. Scene layout

2. Add a handle listener

1. Monitor event changes

Convert from the original mouse series to the touch series

  1. touchstart touch press, equivalent to mousedown
  2. touchmove touch movement, equivalent to mousemove
  3. touchend Touch up, equivalent to mouseup
  4. touchcancel Touch canceled, terminated by other events, equivalent to pressing the ESC key

2. Coordinate setting

When the touch is pressed, the push position changes (use world coordinate conversion), and when the touch is lifted, it returns to the original position (directly set 0, 0 coordinates are the default relative coordinates).
setPosition() sets the coordinates relative to the parent node.

  onTouchMove(e:cc.Event.EventTouch){

         // e.getLocation() is the clicked location, which is the world coordinate. // The world coordinate needs to be converted to the local coordinate. let parent=this.node.parent; // Parent node (circular chassis)
        let pos:cc.Vec2=parent.convertToNodeSpaceAR(e.getLocation());
        this.node.setPosition(pos);

    }

    onTouchCancel(){
      this.node.setPosition(cc.v3(0,0,0));
    }

3. Confine the handle to the tray

Use the azimuth angle to locate the edge position. The pos.normalize() method returns the (cos, sin) of the point relative to (0, 0) and returns a Vec2 object.

let parent=this.node.parent; // Parent node (circular chassis)
let pos:cc.Vec2=parent.convertToNodeSpaceAR(e.getLocation());
// The position of the point (cos, sin)
let direction:cc.Vec2=pos.normalize();
// Limit to within the boundary let maxR = 100-20;   
//The distance from the clicked point to the center of the tray let r : number = cc.Vec2.distance(pos, cc.v2(0,0));

if( r > maxR )
{
	pos.x = maxR * direction.x; 
	pos.y = maxR * direction.y;
}
// cc.log("Relative position: " + pos.x + ", " + pos.y);
this.node.setPosition( pos);

3. Add car control

1. Rotation of the car

cc.Node.angle
Indicates the rotation angle, counterclockwise is positive. The official recommendation is not to use cc.Node.rotationa.signAngle( b)
a and b are two vectors, and the return value is the angle between a and b (in radians).
radian = a.signAngle(b)
(1) a is clockwise from b: the angle is positive
(2) a is counterclockwise from b: the angle is negative

Rotation implementation:
Add attribute car: cc.Node=null; to get the car node.
cc.find() Note that the parameter uses a slash "/" to separate the division sign, otherwise it will not be recognized

onLoad () {
     this.car=cc.find("Canvas/car");
}
let radian = pos.signAngle (cc.v2 (1,0)); //Calculate the angle between the click position and the horizontal let ang = radian / Math.PI * 180; //Convert radians to angles this.car.angle = -ang; //Counterclockwise is positive, so adjust to clockwise here

2. Movement of the Car

  1. Add a forward animation to the car's script, and in the update(dt) method, add the corresponding velocity components on the x and y axes to x and y in each frame.
  2. Get the script under the car node in the handle control script. The direction angle obtained above is passed into the car script. Control the movement of the car by controlling the direction.

Car movement script

direction: cc.Vec2 = null;
speed: number = 3;

onLoad() {

}

start() {

}

update(dt) {
	if (this.direction == null) return; //Standstill let dx = this.speed * this.direction.x;
	let dy = this.speed * this.direction.y;

	let pos = this.node.getPosition();
	pos.x += dx;
	pos.y += dy;
	this.node.setPosition(pos);
}

Gamepad control script

car: cc.Node = null;
carscript: cc.Component = null;
// LIFE-CYCLE CALLBACKS:

onLoad() {
	this.car = cc.find("Canvas/car");
	this.carscript = this.car.getComponent("CarMove");
}

start() {
	this.node.on('touchstart', this.onTouchStart, this);
	this.node.on('touchmove', this.onTouchMove, this);
	this.node.on('touchend', this.onTouchCancel, this);
	this.node.on('touchcancel', this.onTouchCancel, this);
}

onTouchStart() {

}

onTouchMove(e: cc.Event.EventTouch) {

	// e.getLocation() is the clicked location, which is the world coordinate. // The world coordinate needs to be converted to local coordinate. // let parent=this.node.parent;// Parent node (circular chassis)
	// let pos:cc.Vec2=parent.convertToNodeSpaceAR(e.getLocation());
	// this.node.setPosition(pos);

	let parent = this.node.parent; // Parent node (circular chassis)
	let pos: cc.Vec2 = parent.convertToNodeSpaceAR(e.getLocation());
	// The position of the point (cos, sin)
	let direction: cc.Vec2 = pos.normalize();
	// Limit to within the boundary let maxR = 100 - 20;

	let r: number = cc.Vec2.distance(pos, cc.v2(0, 0));

	if (r > maxR) {
		pos.x = maxR * direction.x;
		pos.y = maxR * direction.y;
	}
	// cc.log("Relative position: " + pos.x + ", " + pos.y);
	this.node.setPosition(pos);

	let radian = pos.signAngle(cc.v2(1, 0)); //Calculate the angle between the click position and the horizontal let ang = radian / Math.PI * 180; //Convert radians to angles this.car.angle = -ang; //Counterclockwise is positive, so adjust to clockwise here this.carscript.direction = direction;

}

onTouchCancel() {
	this.node.setPosition(cc.v3(0, 0, 0));
	//Set the direction to null to stop the car this.carscript.direction = null;

}
// update (dt) {}

Final result

The above is the details of how to use the game controller in CocosCreator. For more information about CocosCreator controller examples, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • CocosCreator Getting Started Tutorial: Network Communication
  • Cocos2d-x 3.x Getting Started Tutorial (Part 2): Node Class
  • Cocos2d-x 3.x Getting Started Tutorial (I): Basic Concepts
  • Cocos2d-x Getting Started Tutorial (Detailed Examples and Explanations)
  • Detailed explanation of making shooting games with CocosCreator
  • How to draw a cool radar chart in CocosCreator
  • Detailed explanation of CocosCreator MVC architecture
  • Detailed explanation of CocosCreator message distribution mechanism
  • How to create WeChat games with CocosCreator
  • Detailed explanation of how CocosCreator system events are generated and triggered
  • Detailed explanation of CocosCreator Huarongdao digital puzzle
  • CocosCreator Getting Started Tutorial: Making Your First Game with TS

<<:  Analysis of MySQL joint index function and usage examples

>>:  Detailed example of database operation object model in Spring jdbc

Recommend

Web lesson plans, lesson plans for beginners

Teaching Topics Web page Applicable grade Second ...

How to check the hard disk size and mount the hard disk in Linux

There are two types of hard disks in Linux: mount...

MySQL conditional query and or usage and priority example analysis

This article uses examples to illustrate the usag...

Use of Linux crontab command

1. Command Introduction The contab (cron table) c...

Example of making XML online editor using js

Table of contents Preface The need for online XML...

How to stop CSS animation midway and maintain the posture

Preface I once encountered a difficult problem. I...

How to set up ssh password-free login to Linux server

Every time you log in to the test server, you alw...

A brief analysis of the matching priority of Nginx configuration location

Preface The location in the server block in the N...

Analysis and solution of data loss during Vue component value transfer

Preface In the previous article Two data types in...

MySQL GROUP_CONCAT limitation solution

effect: The GROUP_CONCAT function can concatenate...

Solution to 700% CPU usage of Linux process that cannot be killed

Table of contents 1. Problem Discovery 2. View de...

How to add Lua module to Nginx

Install lua wget http://luajit.org/download/LuaJI...

The difference between HTML iframe and frameset_PowerNode Java Academy

Introduction 1.<iframe> tag: iframe is an i...