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

Specific use of MySQL binlog_ignore_db parameter

Preface: After studying the previous article, we ...

MySQL 5.6 installation steps with pictures and text

MySQL is an open source small relational database...

SQL serial number acquisition code example

This article mainly introduces the sql serial num...

Implementation of FIFO in Linux process communication

FIFO communication (first in first out) FIFO name...

I have compiled a few cool design sites that I think are good.

You must have inspiration to design a website. Goo...

Sending emails in html is easy with Mailto

Recently, I added a click-to-send email function t...

MySQL 5.7.17 installation and configuration graphic tutorial

The blogger said : I have been writing a series o...

Several reasons for not compressing HTML

The reason is simple: In HTML documents, multiple ...

Linux /etc/network/interfaces configuration interface method

The /etc/network/interfaces file in Linux is used...

jQuery implements shopping cart function

This article example shares the specific code of ...

Deploy grafana+prometheus configuration using docker

docker-compose-monitor.yml version: '2' n...