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

12 Useful Array Tricks in JavaScript

Table of contents Array deduplication 1. from() s...

React's method of realizing secondary linkage

This article shares the specific code of React to...

Color matching techniques and effect display for beauty and styling websites

Color is one of the most important elements for a...

Common tags in XHTML

What are XHTML tags? XHTML tag elements are the b...

Linux uses iptables to limit multiple IPs from accessing your server

Preface In the Linux kernel, netfilter is a subsy...

A detailed discussion of evaluation strategies in JavaScript

Table of contents A chestnut to cover it Paramete...

Analysis of the principles of docker containers

Table of contents 01 What is the essence of a con...

How to find websites with SQL injection (must read)

Method 1: Use Google advanced search, for example...

js+css to realize three-level navigation menu

This article example shares the specific code of ...

A brief introduction to web2.0 products and functions

<br />What is web2.0? Web2.0 includes those ...

Monitor the size change of a DOM element through iframe

A common problem encountered during the developme...

How to install and configure WSL on Windows

What is WSL Quoting a passage from Baidu Encyclop...