sfdemo / js /char.js
HelloSun's picture
Build playable pure HTML and JavaScript fight demo
c7b3e0f verified
Raw History Blame Contribute Delete
15.7 kB
// char.js - Character state machine, hit resolution, push, juggle, guard.
// Ported in structure from Ikemen-GO (MIT) src/char.go + src/state.go.
import * as E from './engine.js';
let NEXT_ID = 1;
export class HitDef {
constructor(o = {}) {
this.attr = o.attr || 0;
this.damage = o.damage || 0;
this.guard = o.guard || null; // { damage, pausetime, vel: [x,y] }
this.animtype = o.animtype || E.AT_HA;
this.affectteam = o.affectteam || 'enemy';
this.hitflag = o.hitflag || 'HF'; // MA/HA/LA/M/H/F/P
this.groundhit = o.groundhit ?? 0;
this.groundslide = o.groundslide ?? false;
this.downhit = o.downhit ?? 0;
this.downslide = o.downslide ?? false;
this.airhit = o.airhit ?? 0;
this.priority = o.priority || 1;
this.pausetime = o.pausetime ?? 10;
this.sparkno = o.sparkno ?? 1;
this.sparkx = o.sparkx ?? -50;
this.sparky = o.sparky ?? -50;
this.hitdefsparkscale = o.hitdefsparkscale ?? 1;
this.vel = o.vel || [0, 0];
this.friction = o.friction ?? 0;
this.koratio = o.koratio ?? 1.4;
this.getpower = o.getpower || [0, 0];
this.gethit_ground_type = o.gethit_ground_type || 'high';
this.juggle = o.juggle ?? 0;
this.reversal = o.reversal || false;
this.reversalattr = o.reversalattr || 0;
this.air = o.air || {};
this.air.juggle = o.air?.juggle ?? 0;
this.air.velocity = o.air?.velocity || [0, 0];
this.air.target_facing = o.air?.target_facing ?? 1;
this.down_bounce_offset_y = o.down_bounce_offset_y ?? 0;
this.id = o.id ?? 0;
}
testAttr(attr) { return (this.attr & attr) !== 0; }
isProjectile() { return (this.attr & E.AT_AP) !== 0; }
}
/**
* Input buffer + command recognizer.
* Ports MUGEN command-state logic (N/S/C/A/U + BS/FS/SS/CS) from system.cmd,
* plus the documented `;` and `/` separator shorthands.
*/
export class InputBuffer {
constructor() {
this.buttons = new Set(); // up, down, left, right, a, b, c, x, y, z
this.prev = new Set();
this.held = { left: 0, right: 0, up: 0, down: 0, a: 0, b: 0, c: 0, x: 0, y: 0, z: 0 };
this.dirX = 0;
this.dirY = 0;
this.lastDir = 'n';
this.buffers = []; // [{cmd, frames}]
this.state = 'S';
this.bs = 'N'; this.fs = 'N'; this.ss = 'N'; this.cs = 'N';
this.queue = [];
}
poll(keys) {
this.prev = this.buttons;
this.buttons = keys;
for (const k in this.held) {
if (this.buttons.has(k) && !this.prev.has(k)) this.held[k] = 1;
else if (this.buttons.has(k)) this.held[k]++;
else this.held[k] = 0;
}
const f = this.buttons.has('right') ? 1 : this.buttons.has('left') ? -1 : 0;
if (f !== 0) this.lastDir = f > 0 ? 'f' : 'b';
this.dirX = f;
this.dirY = this.buttons.has('up') ? 1 : (this.buttons.has('down') ? -1 : 0);
}
dir() {
if (this.dirX === 0 && this.dirY === 0) return 'n';
return (this.dirY > 0 ? 'u' : '') + (this.dirY < 0 ? 'd' : '') +
(this.dirX < 0 ? 'b' : '') + (this.dirX > 0 ? 'f' : '');
}
/**
* Feed a command list (MUGEN .cmd style) and return true on trigger.
* Command spec: { command: 'x', dir: 'f', trigger: 'S', hold: 1, buffer: 1 }
* Multiple tokens joined by ',' are ORed.
*/
trigger(list, char) {
const d = this.dir();
for (let i = list.length - 1; i >= 0; i--) {
const c = list[i];
const f = (c.facingOnly && char.facing !== 1) ? -c.facing : c.facing;
if (!c.dir) continue;
if (!dirMatch(d, c.dir, f, this.dirX)) continue;
const btn = c.command;
if (btn && !this.buttons.has(btn)) continue;
if (c.trigger === 'S' && char.stateNo !== c.state) continue;
if (c.trigger === 'C' && char.crouching) continue;
if (c.trigger === 'A' && char.stateType === E.ST_A) continue;
if (c.hold && this.held[btn] < c.hold) continue;
return true;
}
return false;
}
/** Motion-dash detection: f,f / b,b */
dashFwd() { return this.buffers.includes('ff'); }
dashBack() { return this.buffers.includes('bb'); }
}
function dirMatch(cur, want, facing, dirX) {
if (want === '*') return true;
if (want === 'n') return cur === 'n';
if (want === 'f') return dirX > 0 && (cur === 'f' || cur === 'uf' || cur === 'df');
if (want === 'b') return dirX < 0 && (cur === 'b' || cur === 'ub' || cur === 'db');
if (want === 'u') return cur === 'u' || cur === 'uf' || cur === 'ub';
if (want === 'd') return cur === 'd' || cur === 'df' || cur === 'db';
if (want === 'uf') return cur === 'uf';
if (want === 'ub') return cur === 'ub';
if (want === 'df') return cur === 'df';
if (want === 'db') return cur === 'db';
return false;
}
export class Clsn {
constructor(type, box, index = 0) {
this.type = type; // 'hit' | 'hurt' | 'throw' | 'push'
this.box = box;
this.index = index;
this.enabled = true;
this.reduced = false;
this.fusion = false;
this.inverseboth = false;
this.fusionpair = false;
this.guard = null;
this.groundhit = 0;
this.airhit = 0;
this.hit = null;
this.depth = 0;
}
}
export class Char {
constructor(def, playerID, teamside, playerNo) {
this.def = def;
this.data = def.data;
this.id = NEXT_ID++;
this.playerID = playerID; // slot index (0..5)
this.teamside = teamside; // 0 = P1 team, 1 = P2 team
this.playerNo = playerNo; // 1 or 2 (-1 for helpers)
this.pos = [0, 0, 0];
this.vel = [0, 0, 0];
this.accel = [0, 0, 0];
this.stateNo = 0;
this.stateType = 0;
this.prevStateNo = 0;
this.moveType = E.MT_I;
this.stateTime = 0;
this.acttmp = 0;
this.facing = 1;
this.airborne = false;
this.crouching = false;
this.juggle = 0;
this.airjumpNum = 0;
this.airjumpUsed = 0;
this.yaccelOverride = 0;
this.velFreezeY = false;
this.hp = this.data.health;
this.power = 0;
this.powerMax = this.data.powerMax;
this.stun = 0;
this.stunMax = this.data.stunMax;
this.dizzy = 0;
this.hitdef = new HitDef();
this.hasHitdef = false;
this.hitCountThisAttack = 0;
this.hitId = 0;
this.hitChainId = 0;
this.moveContacted = 0;
this.moveHits = 0;
this.moveContactTime = 0;
this.guardState = false;
this.guarding = false;
this.guardingPre = false;
this.hitdefState = 0;
this.cflags = new Set();
this.hitFlash = 0;
this.invuln = 0;
this.pause = 0; // hitstop
this.pauseMovetime = 0;
this.input = new InputBuffer();
this.clsn = [];
this.animName = 'stand';
this.animFrame = 0;
this.animTime = 0;
this.pushedBy = 0;
this.pushed = false;
this.pushVel = 0;
this.comboCount = 0;
this.comboDmg = 0;
this.lastHitFrame = -999;
this.cmd = { dir: 'n', buffer: [], state: 'S', bs: 'N' };
this.stateChangeFlag = false;
this.dizzyFlag = false;
this.koFlag = false;
this.walkVel = 0;
this.juggleIds = new Map();
this.time = 0;
}
/* ---------------- state machine ---------------- */
setState(no, type) {
this.prevStateNo = this.stateNo;
this.stateNo = no;
this.stateType = type;
this.stateTime = 0;
this.stateChangeFlag = true;
this.acttmp = this.acttmp || 0;
this.moveContacted = 0;
this.moveContactTime = 0;
this.hitCountThisAttack = 0;
this.airjumpUsed = 0;
this.yaccelOverride = 0;
this.velFreezeY = false;
this.hasHitdef = false;
this.hitdef = new HitDef();
this.hitId = 0;
this.animTime = 0;
}
changeState(no, type) {
if (!this.canChangeState()) return false;
this.setState(no, type);
return true;
}
canChangeState() {
if (this.moveType === E.MT_I) return true;
if (this.stateTime === 0) return true;
return false;
}
setMoveType(t) { this.moveType = t; }
/* ---------------- per-frame update ---------------- */
update(stage, sys) {
this.time++;
// hitstop: freeze this char
if (this.pause > 0) {
this.pause--;
this.acttmp = 1;
return;
}
const st = this.def.states[this.stateNo];
this.stateTime++;
this.acttmp = this.moveType === E.MT_H || this.moveType === E.MT_U ? 1 : 0;
// hit-flash decay
if (this.hitFlash > 0) this.hitFlash--;
if (this.invuln > 0) this.invuln--;
if (this.stun > 0) this.stun -= this.data.stun_decay;
// auto face opponent (stage autoturn)
if (stage.autoturn && st && st.faceOpponent !== false && this.moveType !== E.MT_H) {
if (this.stateType === E.ST_S || this.stateType === E.ST_C || this.stateType === E.ST_A) {
const foe = this.nearestEnemy(sys);
if (foe) {
const want = foe.pos[0] > this.pos[0] ? 1 : -1;
if (want !== this.facing && !this.isReversing()) this.facing = want;
}
}
}
// animation
this.updateAnim(st);
// physics is integrated once per frame further below; stateType only
// affects which gravity/friction regime engine.physicsStep applies.
// velocity overrides declared by the state.
// velset/veladd/velmul apply on state entry only (frame 0), which is how
// Ikemen's [Statedef] velset behaves for impulse-style states such as jumps.
// Continuous motion is driven by applyWalk()/air drag instead.
// apply state hitdef (only once, on state entry)
if (this.stateChangeFlag) {
this.stateChangeFlag = false;
if (st && st.velset) {
for (let i = 0; i < 3; i++) if (st.velset[i] !== undefined) this.vel[i] = st.velset[i];
}
if (st && st.veladd) {
for (let i = 0; i < 3; i++) if (st.veladd[i] !== undefined) this.vel[i] += st.veladd[i];
}
if (st && st.velmul) {
for (let i = 0; i < 3; i++) if (st.velmul[i] !== undefined) this.vel[i] *= st.velmul[i];
}
if (st && st.hitdef) {
this.hitdef = new HitDef(st.hitdef);
this.hasHitdef = true;
this.hitCountThisAttack = 0;
if (this.hitdef.air && this.hitdef.air.juggle) this.hitId = ++sys.nextHitId;
this.power = Math.min(this.powerMax, this.power + (st.poweradd || 0));
}
if (st && st.anim) this.setAnim(st.anim);
if (st && st.hitdef_bodypush !== undefined) this.pushFactor = st.hitdef_bodypush;
if (st && st.facehittime !== undefined) this.faceHitTime = st.facehittime;
}
// physics step (always, unless fully frozen)
if (this.stateType !== E.ST_L) {
const prevY = this.pos[1];
E.physicsStep(this);
// ground landing
if (this.pos[1] >= 0) {
this.pos[1] = 0;
if (this.airborne) this.onLand(stage);
this.airborne = false;
this.vel[1] = 0;
} else {
this.airborne = true;
}
}
// push
if (this.pushVel !== 0) {
this.pos[0] += this.pushVel;
this.pushVel *= 0.7;
if (Math.abs(this.pushVel) < 0.05) this.pushVel = 0;
}
// decay combo display
if (sys.frame - this.lastHitFrame > 60) { this.comboCount = 0; this.comboDmg = 0; }
// death / dizzy
if (this.hp <= 0 && !this.koFlag) { this.koFlag = true; this.onKO(stage); }
if (this.stun >= this.stunMax && !this.dizzyFlag && this.hp > 0) {
this.dizzyFlag = true; this.onDizzy(stage);
}
}
onLand(stage) {
if (this.moveType !== E.MT_H) return;
// bounce once off the floor, then go down
if (!this.bounced && this.hitWasAirborne) {
this.bounced = true;
this.vel[1] = -4.6;
this.pos[1] = -0.1;
this.airborne = true;
return;
}
this.changeState(this.data.lyingdown_state, E.ST_L);
}
onKO(stage) {
this.changeState(this.data.ko_state, E.ST_L);
this.cflags.add(E.CF_KO);
this.juggle = 0;
}
onDizzy(stage) {
this.dizzy = 1;
this.changeState(this.data.dizzy_state, E.ST_L);
}
isReversing() {
return !!(this.hitdef && this.hitdef.reversal);
}
/* ---------------- animation ---------------- */
setAnim(name) {
this.animName = name;
this.animTime = 0;
this.animFrame = 0;
this.animEnded = false;
}
updateAnim(st) {
const anims = this.def.anims;
const a = anims[this.animName];
this.animTime++;
if (!a) return;
if (this.animTime >= a.time) {
this.animTime = 0;
this.animFrame++;
if (this.animFrame >= a.frames.length) {
if (a.loop) this.animFrame = 0;
else {
this.animFrame = a.frames.length - 1;
if (!this.animEnded) {
this.animEnded = true;
if (st && st.animdone_to !== undefined) this.onAnimDone();
}
}
}
}
}
onAnimDone() {
const st = this.def.states[this.stateNo];
if (st && st.animdone_to !== undefined) this.changeState(st.animdone_to, st.animdone_type ?? E.ST_U);
}
currentFrame() {
const a = this.def.anims[this.animName];
if (!a) return null;
return a.frames[Math.min(this.animFrame, a.frames.length - 1)];
}
/* ---------------- collision boxes ---------------- */
buildClsn() {
this.clsn.length = 0;
const st = this.def.states[this.stateNo];
if (!st) return;
const mk = (arr, type, depth) => {
for (let i = 0; i < arr.length; i++) this.clsn.push(new Clsn(type, arr[i], i));
};
// hurtbox variant by state type
const hurtboxes =
st.hurtbox ||
(this.stateType === E.ST_C ? this.data.hurtboxes.crouch :
this.stateType === E.ST_A ? this.data.hurtboxes.air
: this.data.hurtboxes.stand);
const pushboxes = st.pushbox || this.data.pushboxes.stand;
const attackboxes = st.hitbox || [];
const throwboxes = st.throwbox || [];
mk(hurtboxes, 'hurt', this.data.depth);
mk(pushboxes, 'push', this.data.depth);
for (const b of attackboxes) {
if (b.visible === false && b.active === false) continue;
const c = new Clsn('hit', b, 0);
c.depth = this.data.attackDepth;
c.hit = this.hasHitdef ? this.hitdef : null;
this.clsn.push(c);
}
for (const b of throwboxes) {
const c = new Clsn('throw', b, 0);
c.depth = this.data.attackDepth;
this.clsn.push(c);
}
}
/** Transform a local box to stage (world) coordinates. */
worldPushBox() {
const st = this.def.states[this.stateNo];
const boxes = (st && st.pushbox) || this.data.pushboxes.stand;
if (!boxes || !boxes.length) return null;
// union of push boxes
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
for (const b of boxes) {
const w = this.worldBox(b);
x0 = Math.min(x0, w[0]); x1 = Math.max(x1, w[2]);
y0 = Math.min(y0, w[1]); y1 = Math.max(y1, w[3]);
}
return [x0, y0, x1, y1];
}
worldBox(box) {
const x = this.pos[0], y = this.pos[1], z = this.pos[2];
const x0 = box[0], x1 = box[2];
// x-axis: local +x points forward when facing = 1
const wx0 = this.facing > 0 ? x + x0 : x - x1;
const wx1 = this.facing > 0 ? x + x1 : x - x0;
// y-axis: local y is negative (up); world y grows down from pos
const wy0 = y + box[1];
const wy1 = y + box[3];
// z (depth) axis scaled into x in the plane perpendicular to screen
return [wx0, wy0, wx1, wy1];
}
nearestEnemy(sys) {
let best = null, bd = Infinity;
for (const c of sys.chars) {
if (c === this) continue;
if (c.teamside === this.teamside) continue;
const d = Math.abs(c.pos[0] - this.pos[0]) + Math.abs(c.pos[1] - this.pos[1]) * 0.3 + Math.abs(c.pos[2] - this.pos[2]) * 0.5;
if (d < bd) { bd = d; best = c; }
}
return best;
}
distanceTo(c) { return Math.abs(c.pos[0] - this.pos[0]); }
}