Changing the "Point" notion to add a notion of "moving" in addition to the notion of direction.

Also, refactoring JOIN_ROOM event to add complete position.
This commit is contained in:
David Négrier 2020-05-22 22:59:43 +02:00
parent f44a44c109
commit ab798b1c09
9 changed files with 101 additions and 88 deletions

View File

@ -89,12 +89,19 @@ export class IoSocketController {
x: user x position on map x: user x position on map
y: user y position on map y: user y position on map
*/ */
socket.on(SockerIoEvent.JOIN_ROOM, (roomId: any, answerFn): void => { socket.on(SockerIoEvent.JOIN_ROOM, (message: any, answerFn): void => {
try { try {
let roomId = message.roomId;
if (typeof(roomId) !== 'string') { if (typeof(roomId) !== 'string') {
socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'}); socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: 'Expected roomId as a string.'});
return; return;
} }
let position = this.hydratePositionReceive(message.position);
if (position instanceof Error) {
socket.emit(SockerIoEvent.MESSAGE_ERROR, {message: position.message});
return;
}
let Client = (socket as ExSocketInterface); let Client = (socket as ExSocketInterface);
@ -106,12 +113,12 @@ export class IoSocketController {
this.leaveRoom(Client); this.leaveRoom(Client);
//join new previous room //join new previous room
let world = this.joinRoom(Client, roomId); let world = this.joinRoom(Client, roomId, position);
//add function to refresh position user in real time. //add function to refresh position user in real time.
//this.refreshUserPosition(Client); //this.refreshUserPosition(Client);
let messageUserJoined = new MessageUserJoined(Client.id, Client.name, Client.character); let messageUserJoined = new MessageUserJoined(Client.id, Client.name, Client.character, Client.position);
socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserJoined); socket.to(roomId).emit(SockerIoEvent.JOIN_ROOM, messageUserJoined);
@ -140,16 +147,13 @@ export class IoSocketController {
// sending to all clients in room except sender // sending to all clients in room except sender
Client.position = position; Client.position = position;
//refresh position of all user in all rooms in real time
//this.refreshUserPosition(Client);
// update position in the world // update position in the world
let world = this.Worlds.get(Client.roomId); let world = this.Worlds.get(Client.roomId);
if (!world) { if (!world) {
console.error("Could not find world with id '", Client.roomId, "'"); console.error("Could not find world with id '", Client.roomId, "'");
return; return;
} }
world.updatePosition(Client, Client.position); world.updatePosition(Client, position);
socket.to(Client.roomId).emit(SockerIoEvent.USER_MOVED, new MessageUserMoved(Client.id, Client.position)); socket.to(Client.roomId).emit(SockerIoEvent.USER_MOVED, new MessageUserMoved(Client.id, Client.position));
} catch (e) { } catch (e) {
@ -182,10 +186,6 @@ export class IoSocketController {
try { try {
let Client = (socket as ExSocketInterface); let Client = (socket as ExSocketInterface);
if (Client.roomId) {
socket.to(Client.roomId).emit(SockerIoEvent.USER_LEFT, socket.id);
}
//leave room //leave room
this.leaveRoom(Client); this.leaveRoom(Client);
@ -238,11 +238,11 @@ export class IoSocketController {
} }
} }
private joinRoom(Client : ExSocketInterface, roomId: string): World { private joinRoom(Client : ExSocketInterface, roomId: string, position: Point): World {
//join user in room //join user in room
Client.join(roomId); Client.join(roomId);
Client.roomId = roomId; Client.roomId = roomId;
Client.position = new Point(-1000, -1000); Client.position = position;
//check and create new world for a room //check and create new world for a room
let world = this.Worlds.get(roomId) let world = this.Worlds.get(roomId)
@ -311,10 +311,10 @@ export class IoSocketController {
//Hydrate and manage error //Hydrate and manage error
hydratePositionReceive(message: any): Point | Error { hydratePositionReceive(message: any): Point | Error {
try { try {
if (!message.x || !message.y || !message.direction) { if (!message.x || !message.y || !message.direction || message.moving === undefined) {
return new Error("invalid point message sent"); return new Error("invalid point message sent");
} }
return new Point(message.x, message.y, message.direction); return new Point(message.x, message.y, message.direction, message.moving);
} catch (err) { } catch (err) {
//TODO log error //TODO log error
return new Error(err); return new Error(err);

View File

@ -1,5 +1,7 @@
import {Point} from "./MessageUserPosition";
import {PointInterface} from "_Model/Websocket/PointInterface";
export class MessageUserJoined { export class MessageUserJoined {
constructor(public userId: string, public name: string, public character: string) { constructor(public userId: string, public name: string, public character: string, public position: PointInterface) {
} }
} }

View File

@ -1,7 +1,7 @@
import {PointInterface} from "./PointInterface"; import {PointInterface} from "./PointInterface";
export class Point implements PointInterface{ export class Point implements PointInterface{
constructor(public x : number, public y : number, public direction : string = "none") { constructor(public x : number, public y : number, public direction : string = "none", public moving : boolean = false) {
} }
} }

View File

@ -6,6 +6,7 @@ import {SetPlayerDetailsMessage} from "./Messages/SetPlayerDetailsMessage";
const SocketIo = require('socket.io-client'); const SocketIo = require('socket.io-client');
import Socket = SocketIOClient.Socket; import Socket = SocketIOClient.Socket;
import {PlayerAnimationNames} from "./Phaser/Player/Animation";
enum EventMessage{ enum EventMessage{
@ -42,20 +43,14 @@ export interface PointInterface {
x: number; x: number;
y: number; y: number;
direction : string; direction : string;
moving: boolean;
} }
export class Point implements PointInterface{ export class Point implements PointInterface{
x: number; constructor(public x : number, public y : number, public direction : string = PlayerAnimationNames.WalkDown, public moving : boolean = false) {
y: number;
direction : string;
constructor(x : number, y : number, direction : string = "none") {
if(x === null || y === null){ if(x === null || y === null){
throw Error("position x and y cannot be null"); throw Error("position x and y cannot be null");
} }
this.x = x;
this.y = y;
this.direction = direction;
} }
} }
@ -84,6 +79,7 @@ export interface MessageUserJoined {
userId: string; userId: string;
name: string; name: string;
character: string; character: string;
position: PointInterface
} }
export interface ListMessageUserPositionInterface { export interface ListMessageUserPositionInterface {
@ -104,7 +100,8 @@ class ListMessageUserPosition {
new Point( new Point(
userPosition.position.x, userPosition.position.x,
userPosition.position.y, userPosition.position.y,
userPosition.position.direction userPosition.position.direction,
userPosition.position.moving
), ),
userPosition.name, userPosition.name,
userPosition.character userPosition.character
@ -133,9 +130,9 @@ export interface ConnexionInterface {
loadMaps(): Promise<any>; loadMaps(): Promise<any>;
joinARoom(roomId: string, character: string): void; joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): void;
sharePosition(x: number, y: number, direction: string, roomId: string, character: string): void; sharePosition(x: number, y: number, direction: string, moving: boolean): void;
positionOfAllUser(): void; positionOfAllUser(): void;
@ -215,20 +212,23 @@ export class Connexion implements ConnexionInterface {
//if try to reconnect with last position //if try to reconnect with last position
if(this.lastRoom) { if(this.lastRoom) {
//join the room //join the room
this.joinARoom( this.joinARoom(this.lastRoom,
this.lastRoom this.lastPositionShared ? this.lastPositionShared.x : 0,
); this.lastPositionShared ? this.lastPositionShared.y : 0,
this.lastPositionShared ? this.lastPositionShared.direction : PlayerAnimationNames.WalkDown,
this.lastPositionShared ? this.lastPositionShared.moving : false);
} }
if(this.lastPositionShared) { /*if(this.lastPositionShared) {
//share your first position //share your first position
this.sharePosition( this.sharePosition(
this.lastPositionShared ? this.lastPositionShared.x : 0, this.lastPositionShared ? this.lastPositionShared.x : 0,
this.lastPositionShared ? this.lastPositionShared.y : 0, this.lastPositionShared ? this.lastPositionShared.y : 0,
this.lastPositionShared.direction this.lastPositionShared.direction,
this.lastPositionShared.moving
); );
} }*/
resolve(this); resolve(this);
}); });
@ -245,31 +245,18 @@ export class Connexion implements ConnexionInterface {
}); });
} }
/** joinARoom(roomId: string, startX: number, startY: number, direction: string, moving: boolean): void {
* this.socket.emit(EventMessage.JOIN_ROOM, { roomId, position: {x: startX, y: startY, direction, moving }}, (userPositions: MessageUserPositionInterface[]) => {
* @param roomId
* @param character
*/
joinARoom(roomId: string): void {
this.socket.emit(EventMessage.JOIN_ROOM, roomId, (userPositions: MessageUserPositionInterface[]) => {
this.GameManager.initUsersPosition(userPositions); this.GameManager.initUsersPosition(userPositions);
}); });
this.lastRoom = roomId; this.lastRoom = roomId;
} }
/** sharePosition(x : number, y : number, direction : string, moving: boolean) : void{
*
* @param x
* @param y
* @param character
* @param roomId
* @param direction
*/
sharePosition(x : number, y : number, direction : string = "none") : void{
if(!this.socket){ if(!this.socket){
return; return;
} }
let point = new Point(x, y, direction); let point = new Point(x, y, direction, moving);
this.lastPositionShared = point; this.lastPositionShared = point;
this.socket.emit(EventMessage.USER_POSITION, point); this.socket.emit(EventMessage.USER_POSITION, point);
} }
@ -279,11 +266,11 @@ export class Connexion implements ConnexionInterface {
* [ * [
* { * {
* userId: <string>, * userId: <string>,
* roomId: <string>,
* position: { * position: {
* x : <number>, * x : <number>,
* y : <number>, * y : <number>,
* direction: <string> * direction: <string>,
* moving: <bool>
* } * }
* }, * },
* ... * ...

View File

@ -26,7 +26,7 @@ export const PLAYER_RESOURCES: Array<any> = [
export class PlayableCaracter extends Phaser.Physics.Arcade.Sprite { export class PlayableCaracter extends Phaser.Physics.Arcade.Sprite {
private bubble: SpeechBubble; private bubble: SpeechBubble;
private playerName: BitmapText; private readonly playerName: BitmapText;
public PlayerValue: string; public PlayerValue: string;
public PlayerTexture: string; public PlayerTexture: string;

View File

@ -16,6 +16,7 @@ export enum StatusGameManagerEnum {
export interface HasMovedEvent { export interface HasMovedEvent {
direction: string; direction: string;
moving: boolean;
x: number; x: number;
y: number; y: number;
} }
@ -71,8 +72,8 @@ export class GameManager {
this.status = StatusGameManagerEnum.CURRENT_USER_CREATED; this.status = StatusGameManagerEnum.CURRENT_USER_CREATED;
} }
joinRoom(sceneKey : string){ joinRoom(sceneKey: string, startX: number, startY: number, direction: string, moving: boolean){
this.ConnexionInstance.joinARoom(sceneKey); this.ConnexionInstance.joinARoom(sceneKey, startX, startY, direction, moving);
} }
onUserJoins(message: MessageUserJoined): void { onUserJoins(message: MessageUserJoined): void {
@ -80,7 +81,7 @@ export class GameManager {
userId: message.userId, userId: message.userId,
character: message.character, character: message.character,
name: message.name, name: message.name,
position: new Point(-1000, -1000) position: message.position
} }
this.currentGameScene.addPlayer(userMessage); this.currentGameScene.addPlayer(userMessage);
} }
@ -159,7 +160,7 @@ export class GameManager {
} }
pushPlayerPosition(event: HasMovedEvent) { pushPlayerPosition(event: HasMovedEvent) {
this.ConnexionInstance.sharePosition(event.x, event.y, event.direction); this.ConnexionInstance.sharePosition(event.x, event.y, event.direction, event.moving);
} }
loadMap(mapUrl: string, scene: ScenePlugin): string { loadMap(mapUrl: string, scene: ScenePlugin): string {

View File

@ -13,6 +13,7 @@ import Texture = Phaser.Textures.Texture;
import Sprite = Phaser.GameObjects.Sprite; import Sprite = Phaser.GameObjects.Sprite;
import CanvasTexture = Phaser.Textures.CanvasTexture; import CanvasTexture = Phaser.Textures.CanvasTexture;
import {AddPlayerInterface} from "./AddPlayerInterface"; import {AddPlayerInterface} from "./AddPlayerInterface";
import {PlayerAnimationNames} from "../Player/Animation";
export enum Textures { export enum Textures {
Player = "male1" Player = "male1"
@ -273,16 +274,17 @@ export class GameScene extends Phaser.Scene {
this.startX, this.startX,
this.startY, this.startY,
this.GameManager.getPlayerName(), this.GameManager.getPlayerName(),
this.GameManager.getCharacterSelected() this.GameManager.getCharacterSelected(),
PlayerAnimationNames.WalkDown,
false
); );
this.CurrentPlayer.initAnimation();
//create collision //create collision
this.createCollisionWithPlayer(); this.createCollisionWithPlayer();
this.createCollisionObject(); this.createCollisionObject();
//join room //join room
this.GameManager.joinRoom(this.scene.key); this.GameManager.joinRoom(this.scene.key, this.startX, this.startY, PlayerAnimationNames.WalkDown, false);
//listen event to share position of user //listen event to share position of user
this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this)) this.CurrentPlayer.on(hasMovedEventName, this.pushPlayerPosition.bind(this))
@ -415,9 +417,10 @@ export class GameScene extends Phaser.Scene {
addPlayerData.position.x, addPlayerData.position.x,
addPlayerData.position.y, addPlayerData.position.y,
addPlayerData.name, addPlayerData.name,
addPlayerData.character addPlayerData.character,
addPlayerData.position.direction,
addPlayerData.position.moving
); );
player.initAnimation();
this.MapPlayers.add(player); this.MapPlayers.add(player);
this.MapPlayersByKey.set(player.userId, player); this.MapPlayersByKey.set(player.userId, player);
player.updatePosition(addPlayerData.position); player.updatePosition(addPlayerData.position);
@ -429,6 +432,7 @@ export class GameScene extends Phaser.Scene {
} }
public removePlayer(userId: string) { public removePlayer(userId: string) {
console.log('Removing player ', userId)
let player = this.MapPlayersByKey.get(userId); let player = this.MapPlayersByKey.get(userId);
if (player === undefined) { if (player === undefined) {
console.error('Cannot find user with id ', userId); console.error('Cannot find user with id ', userId);

View File

@ -14,7 +14,6 @@ export enum PlayerAnimationNames {
WalkLeft = 'left', WalkLeft = 'left',
WalkUp = 'up', WalkUp = 'up',
WalkRight = 'right', WalkRight = 'right',
None = 'none',
} }
export const getPlayerAnimations = (name: string = Textures.Player): AnimationData[] => { export const getPlayerAnimations = (name: string = Textures.Player): AnimationData[] => {
@ -48,11 +47,3 @@ export const getPlayerAnimations = (name: string = Textures.Player): AnimationDa
repeat: -1 repeat: -1
}]; }];
}; };
export const playAnimation = (Player : Phaser.GameObjects.Sprite, direction : string) => {
if (direction !== PlayerAnimationNames.None && (!Player.anims.currentAnim || Player.anims.currentAnim.key !== direction)) {
Player.anims.play(direction);
} else if (direction === PlayerAnimationNames.None && Player.anims.currentAnim) {
Player.anims.stop();
}
}

View File

@ -1,4 +1,4 @@
import {getPlayerAnimations, playAnimation, PlayerAnimationNames} from "./Animation"; import {getPlayerAnimations, PlayerAnimationNames} from "./Animation";
import {GameScene, Textures} from "../Game/GameScene"; import {GameScene, Textures} from "../Game/GameScene";
import {MessageUserPositionInterface, PointInterface} from "../../Connexion"; import {MessageUserPositionInterface, PointInterface} from "../../Connexion";
import {ActiveEventList, UserInputEvent, UserInputManager} from "../UserInput/UserInputManager"; import {ActiveEventList, UserInputEvent, UserInputManager} from "../UserInput/UserInputManager";
@ -7,14 +7,12 @@ import {PlayableCaracter} from "../Entity/PlayableCaracter";
export const hasMovedEventName = "hasMoved"; export const hasMovedEventName = "hasMoved";
export interface CurrentGamerInterface extends PlayableCaracter{ export interface CurrentGamerInterface extends PlayableCaracter{
initAnimation() : void;
moveUser(delta: number) : void; moveUser(delta: number) : void;
say(text : string) : void; say(text : string) : void;
} }
export interface GamerInterface extends PlayableCaracter{ export interface GamerInterface extends PlayableCaracter{
userId : string; userId : string;
initAnimation() : void;
updatePosition(position: PointInterface): void; updatePosition(position: PointInterface): void;
say(text : string) : void; say(text : string) : void;
} }
@ -22,7 +20,8 @@ export interface GamerInterface extends PlayableCaracter{
export class Player extends PlayableCaracter implements CurrentGamerInterface, GamerInterface { export class Player extends PlayableCaracter implements CurrentGamerInterface, GamerInterface {
userId: string; userId: string;
userInputManager: UserInputManager; userInputManager: UserInputManager;
previousMove: string; previousDirection: string;
wasMoving: boolean;
constructor( constructor(
userId: string, userId: string,
@ -30,7 +29,9 @@ export class Player extends PlayableCaracter implements CurrentGamerInterface, G
x: number, x: number,
y: number, y: number,
name: string, name: string,
PlayerTexture: string = Textures.Player PlayerTexture: string,
direction: string,
moving: boolean
) { ) {
super(Scene, x, y, PlayerTexture, name, 1); super(Scene, x, y, PlayerTexture, name, 1);
@ -42,9 +43,18 @@ export class Player extends PlayableCaracter implements CurrentGamerInterface, G
//the current player model should be push away by other players to prevent conflict //the current player model should be push away by other players to prevent conflict
this.setImmovable(false); this.setImmovable(false);
this.initAnimation();
console.warn("Start direction for added player ", direction)
console.warn("Position ", x, y)
/*this.play(`${PlayerTexture}-${direction}`, true);
if (!moving) {
this.stop();
}*/
this.playAnimation(direction, moving);
} }
initAnimation(): void { private initAnimation(): void {
getPlayerAnimations(this.PlayerTexture).forEach(d => { getPlayerAnimations(this.PlayerTexture).forEach(d => {
this.scene.anims.create({ this.scene.anims.create({
key: d.key, key: d.key,
@ -58,6 +68,7 @@ export class Player extends PlayableCaracter implements CurrentGamerInterface, G
moveUser(delta: number): void { moveUser(delta: number): void {
//if user client on shift, camera and player speed //if user client on shift, camera and player speed
let direction = null; let direction = null;
let moving = false;
let activeEvents = this.userInputManager.getEventListForGameTick(); let activeEvents = this.userInputManager.getEventListForGameTick();
let speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9; let speedMultiplier = activeEvents.get(UserInputEvent.SpeedUp) ? 25 : 9;
@ -67,39 +78,56 @@ export class Player extends PlayableCaracter implements CurrentGamerInterface, G
let y = 0; let y = 0;
if (activeEvents.get(UserInputEvent.MoveUp)) { if (activeEvents.get(UserInputEvent.MoveUp)) {
y = - moveAmount; y = - moveAmount;
direction = `${this.PlayerTexture}-${PlayerAnimationNames.WalkUp}`; direction = PlayerAnimationNames.WalkUp;
moving = true;
} else if (activeEvents.get(UserInputEvent.MoveDown)) { } else if (activeEvents.get(UserInputEvent.MoveDown)) {
y = moveAmount; y = moveAmount;
direction = `${this.PlayerTexture}-${PlayerAnimationNames.WalkDown}`; direction = PlayerAnimationNames.WalkDown;
moving = true;
} }
if (activeEvents.get(UserInputEvent.MoveLeft)) { if (activeEvents.get(UserInputEvent.MoveLeft)) {
x = -moveAmount; x = -moveAmount;
direction = `${this.PlayerTexture}-${PlayerAnimationNames.WalkLeft}`; direction = PlayerAnimationNames.WalkLeft;
moving = true;
} else if (activeEvents.get(UserInputEvent.MoveRight)) { } else if (activeEvents.get(UserInputEvent.MoveRight)) {
x = moveAmount; x = moveAmount;
direction = `${this.PlayerTexture}-${PlayerAnimationNames.WalkRight}`; direction = PlayerAnimationNames.WalkRight;
moving = true;
} }
if (x !== 0 || y !== 0) { if (x !== 0 || y !== 0) {
this.move(x, y); this.move(x, y);
this.emit(hasMovedEventName, {direction, x: this.x, y: this.y}); this.emit(hasMovedEventName, {moving, direction, x: this.x, y: this.y});
} else { } else {
if (this.previousMove !== PlayerAnimationNames.None) { if (this.wasMoving) {
direction = PlayerAnimationNames.None; //direction = PlayerAnimationNames.None;
this.stop(); this.stop();
this.emit(hasMovedEventName, {direction, x: this.x, y: this.y}); this.emit(hasMovedEventName, {moving, direction: this.previousDirection, x: this.x, y: this.y});
} }
} }
if (direction !== null) { if (direction !== null) {
this.previousMove = direction; this.previousDirection = direction;
} }
this.wasMoving = moving;
} }
//todo: put this method into the NonPlayer class instead //todo: put this method into the NonPlayer class instead
updatePosition(position: PointInterface): void { updatePosition(position: PointInterface): void {
playAnimation(this, position.direction); this.playAnimation(position.direction, position.moving);
this.setX(position.x); this.setX(position.x);
this.setY(position.y); this.setY(position.y);
this.setDepth(position.y); this.setDepth(position.y);
} }
private playAnimation(direction : string, moving: boolean): void {
if (moving && (!this.anims.currentAnim || this.anims.currentAnim.key !== direction)) {
this.anims.play(this.PlayerTexture+'-'+direction);
} else if (!moving) {
/*if (this.anims.currentAnim) {
this.anims.stop();
}*/
this.anims.play(this.PlayerTexture+'-'+direction);
this.anims.stop();
}
}
} }