In the previous article we set up the robot physics object, let's take a look at the corresponding logic code.
Enter Xcode, create new robot and arm classes, and inherit from the Ccnode and Ccsprite classes, respectively. The code is all left blank and then implemented later.
Let's take a look at how this robot interacts with the player. When the player touches the robot arm and moves, it rotates the arm in the center of the joint. Because the front in the Spritebuilder limits the range of joint rotation, so don't worry about the joints rotating to "strange" angle.
The user interaction is first opened in the initialization method of the ARM.M:
self.userInteractionEnabledYES;
Create a new instance variable _touchpoint in the arm class:
@implementation Arm{ CGPoint _touchPoint;}
Add a touch callback method, first Touchbegan:
-(void)touchBegan:(CCTouch *)touch withEvent:(CCTouchEvent *)event{ CGPoint location = [[CCDirector sharedDirector] convertTouchToGL:touch]; _touchPoint = location;}
Here the position of the first touch is used to compare the coordinates after the move, thus determining the direction of the selection.
Then the Touchmoved method:
-(void ) touchMoved: ( Cctouch *) Touch withevent: (cctouchevent *) event{cgpoint location = [[Ccdirector sh Areddirector] Converttouchtogl:touch]; Movedirection direction = Armmovedirectiondown; if (Location.y > _touchpoint.y ) {direction = Armmovedirectionup; }else if (location .y < _touchpoint.y ) {direction = Armmovedi Rectiondown; } [self movearm:direction];}
Let's take a quick look at this method: make a touch move position, compare it to the previously saved position, just determine the value of the y-axis: If it is greater than the previous Y-value, it will rotate upward, otherwise it will rotate downward. Finally, rotate the arm according to the direction of rotation. Here the rotation direction is an enumeration value because , for example, we will see a big problem with touching the arm rotation, and need to touch the screen to select the arm. Here we put it in a generic header file, creating a new Comm.h header file with the following content:
#ifndef ShootBall_Comm_h#define ShootBall_Comm_henum { armMoveDirectionUp, armMoveDirectionDown}MoveDirection;#endif
The header file is then included in all classes that need to use the enumeration definition.
In the next article, we will see how the Movearm method, which is not yet covered in the above code, is implemented;)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
(no.00003) iOS games simple robot projection game forming Kee (v)