Feature/physics and tilemap enhancement (#247)
* feat(behavior-tree,tilemap): 修复编辑器连线缩放问题并增强插件系统 * feat(node-editor,blueprint): 新增通用节点编辑器和蓝图可视化脚本系统 * feat(editor,tilemap): 优化编辑器UI样式和Tilemap编辑器功能 * fix: 修复CodeQL安全警告和CI类型检查错误 * fix: 修复CodeQL安全警告和CI类型检查错误 * fix: 修复CodeQL安全警告和CI类型检查错误
This commit is contained in:
@@ -23,19 +23,40 @@ import type { Vector2 } from '../types/Physics2DTypes';
|
||||
@ECSComponent('BoxCollider2D')
|
||||
@Serializable({ version: 1, typeId: 'BoxCollider2D' })
|
||||
export class BoxCollider2DComponent extends Collider2DBase {
|
||||
private _width: number = 10;
|
||||
private _height: number = 10;
|
||||
|
||||
/**
|
||||
* 矩形宽度(半宽度的2倍)
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'number', label: 'Width', min: 0.01, step: 0.1 })
|
||||
public width: number = 10;
|
||||
public get width(): number {
|
||||
return this._width;
|
||||
}
|
||||
|
||||
public set width(value: number) {
|
||||
if (this._width !== value) {
|
||||
this._width = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 矩形高度(半高度的2倍)
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'number', label: 'Height', min: 0.01, step: 0.1 })
|
||||
public height: number = 10;
|
||||
public get height(): number {
|
||||
return this._height;
|
||||
}
|
||||
|
||||
public set height(value: number) {
|
||||
if (this._height !== value) {
|
||||
this._height = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取半宽度
|
||||
@@ -78,6 +99,5 @@ export class BoxCollider2DComponent extends Collider2DBase {
|
||||
public setSize(width: number, height: number): void {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,19 +35,41 @@ export enum CapsuleDirection2D {
|
||||
@ECSComponent('CapsuleCollider2D')
|
||||
@Serializable({ version: 1, typeId: 'CapsuleCollider2D' })
|
||||
export class CapsuleCollider2DComponent extends Collider2DBase {
|
||||
private _radius: number = 3;
|
||||
private _height: number = 10;
|
||||
private _direction: CapsuleDirection2D = CapsuleDirection2D.Vertical;
|
||||
|
||||
/**
|
||||
* 胶囊半径
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'number', label: 'Radius', min: 0.01, step: 0.1 })
|
||||
public radius: number = 3;
|
||||
public get radius(): number {
|
||||
return this._radius;
|
||||
}
|
||||
|
||||
public set radius(value: number) {
|
||||
if (this._radius !== value) {
|
||||
this._radius = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 胶囊总高度(包括两端的半圆)
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'number', label: 'Height', min: 0.01, step: 0.1 })
|
||||
public height: number = 10;
|
||||
public get height(): number {
|
||||
return this._height;
|
||||
}
|
||||
|
||||
public set height(value: number) {
|
||||
if (this._height !== value) {
|
||||
this._height = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 胶囊方向
|
||||
@@ -61,7 +83,16 @@ export class CapsuleCollider2DComponent extends Collider2DBase {
|
||||
{ label: 'Horizontal', value: 1 }
|
||||
]
|
||||
})
|
||||
public direction: CapsuleDirection2D = CapsuleDirection2D.Vertical;
|
||||
public get direction(): CapsuleDirection2D {
|
||||
return this._direction;
|
||||
}
|
||||
|
||||
public set direction(value: CapsuleDirection2D) {
|
||||
if (this._direction !== value) {
|
||||
this._direction = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取半高度(中间矩形部分的一半)
|
||||
@@ -103,7 +134,6 @@ export class CapsuleCollider2DComponent extends Collider2DBase {
|
||||
public setSize(radius: number, height: number): void {
|
||||
this.radius = radius;
|
||||
this.height = height;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,6 +142,5 @@ export class CapsuleCollider2DComponent extends Collider2DBase {
|
||||
*/
|
||||
public setDirection(direction: CapsuleDirection2D): void {
|
||||
this.direction = direction;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,23 @@ import type { Vector2 } from '../types/Physics2DTypes';
|
||||
@ECSComponent('CircleCollider2D')
|
||||
@Serializable({ version: 1, typeId: 'CircleCollider2D' })
|
||||
export class CircleCollider2DComponent extends Collider2DBase {
|
||||
private _radius: number = 5;
|
||||
|
||||
/**
|
||||
* 圆的半径
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'number', label: 'Radius', min: 0.01, step: 0.1 })
|
||||
public radius: number = 5;
|
||||
public get radius(): number {
|
||||
return this._radius;
|
||||
}
|
||||
|
||||
public set radius(value: number) {
|
||||
if (this._radius !== value) {
|
||||
this._radius = value;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
public override getShapeType(): string {
|
||||
return 'circle';
|
||||
@@ -50,6 +61,5 @@ export class CircleCollider2DComponent extends Collider2DBase {
|
||||
*/
|
||||
public setRadius(radius: number): void {
|
||||
this.radius = radius;
|
||||
this._needsRebuild = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ export abstract class Collider2DBase extends Component {
|
||||
* 使用位掩码,可以属于多个层
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'integer', label: 'Collision Layer', min: 0 })
|
||||
@Property({ type: 'collisionLayer', label: 'Collision Layer' })
|
||||
public collisionLayer: number = CollisionLayer2D.Default;
|
||||
|
||||
/**
|
||||
@@ -62,7 +62,7 @@ export abstract class Collider2DBase extends Component {
|
||||
* 使用位掩码
|
||||
*/
|
||||
@Serialize()
|
||||
@Property({ type: 'integer', label: 'Collision Mask', min: 0 })
|
||||
@Property({ type: 'collisionMask', label: 'Collision Mask' })
|
||||
public collisionMask: number = CollisionLayer2D.All;
|
||||
|
||||
// ==================== 偏移 ====================
|
||||
|
||||
@@ -9,6 +9,12 @@
|
||||
import type { IPluginLoader, PluginDescriptor } from '@esengine/editor-core';
|
||||
import { Physics2DEditorModule } from './index';
|
||||
import { PhysicsRuntimeModule } from '../PhysicsRuntimeModule';
|
||||
import { CollisionLayerConfig } from '../services/CollisionLayerConfig';
|
||||
|
||||
// 暴露 CollisionLayerConfig 到全局,供 CollisionLayerField 访问
|
||||
(window as any).__PHYSICS_RAPIER2D__ = {
|
||||
CollisionLayerConfig
|
||||
};
|
||||
|
||||
/**
|
||||
* 插件描述符
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Collision Layer Selector Component
|
||||
* 碰撞层选择器组件
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { CollisionLayerConfig } from '../../services/CollisionLayerConfig';
|
||||
|
||||
interface CollisionLayerSelectorProps {
|
||||
value: number;
|
||||
onChange: (value: number) => void;
|
||||
label?: string;
|
||||
multiple?: boolean;
|
||||
}
|
||||
|
||||
export const CollisionLayerSelector: React.FC<CollisionLayerSelectorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
multiple = false
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [layers, setLayers] = useState(CollisionLayerConfig.getInstance().getLayers());
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const config = CollisionLayerConfig.getInstance();
|
||||
|
||||
useEffect(() => {
|
||||
const handleUpdate = () => {
|
||||
setLayers([...config.getLayers()]);
|
||||
};
|
||||
|
||||
config.addListener(handleUpdate);
|
||||
return () => config.removeListener(handleUpdate);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const getSelectedLayerNames = (): string => {
|
||||
if (!multiple) {
|
||||
const index = config.getLayerIndex(value);
|
||||
return layers[index]?.name ?? 'Default';
|
||||
}
|
||||
|
||||
const selectedNames: string[] = [];
|
||||
for (let i = 0; i < 16; i++) {
|
||||
if ((value & (1 << i)) !== 0) {
|
||||
selectedNames.push(layers[i]?.name ?? `Layer${i}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedNames.length === 0) return 'None';
|
||||
if (selectedNames.length === 16) return 'All';
|
||||
if (selectedNames.length > 3) return `${selectedNames.length} layers`;
|
||||
return selectedNames.join(', ');
|
||||
};
|
||||
|
||||
const handleLayerToggle = (index: number) => {
|
||||
if (multiple) {
|
||||
const bit = 1 << index;
|
||||
const newValue = (value & bit) ? (value & ~bit) : (value | bit);
|
||||
onChange(newValue);
|
||||
} else {
|
||||
onChange(1 << index);
|
||||
setIsOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
onChange(0xFFFF);
|
||||
};
|
||||
|
||||
const handleSelectNone = () => {
|
||||
onChange(0);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="collision-layer-selector" ref={dropdownRef}>
|
||||
{label && <label className="selector-label">{label}</label>}
|
||||
<div className="selector-container">
|
||||
<button
|
||||
className="selector-button"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
type="button"
|
||||
>
|
||||
<span className="selected-text">{getSelectedLayerNames()}</span>
|
||||
<span className="dropdown-arrow">{isOpen ? '▲' : '▼'}</span>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="dropdown-menu">
|
||||
{multiple && (
|
||||
<div className="dropdown-actions">
|
||||
<button onClick={handleSelectAll} type="button">全选</button>
|
||||
<button onClick={handleSelectNone} type="button">全不选</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="dropdown-list">
|
||||
{layers.slice(0, 8).map((layer, index) => {
|
||||
const isSelected = multiple
|
||||
? (value & (1 << index)) !== 0
|
||||
: config.getLayerIndex(value) === index;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={`dropdown-item ${isSelected ? 'selected' : ''}`}
|
||||
onClick={() => handleLayerToggle(index)}
|
||||
>
|
||||
{multiple && (
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => {}}
|
||||
className="layer-checkbox"
|
||||
/>
|
||||
)}
|
||||
<span className="layer-index">{index}</span>
|
||||
<span className="layer-name">{layer.name}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
.collision-layer-selector {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.selector-label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary, #aaa);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.selector-container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.selector-button {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border-color, #333);
|
||||
border-radius: 4px;
|
||||
background: var(--bg-primary, #1a1a1a);
|
||||
color: var(--text-primary, #fff);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.selector-button:hover {
|
||||
border-color: var(--accent-color, #0078d4);
|
||||
}
|
||||
|
||||
.selected-text {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dropdown-arrow {
|
||||
font-size: 8px;
|
||||
margin-left: 8px;
|
||||
color: var(--text-secondary, #888);
|
||||
}
|
||||
|
||||
.dropdown-menu {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
margin-top: 2px;
|
||||
background: var(--bg-secondary, #1e1e1e);
|
||||
border: 1px solid var(--border-color, #333);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
z-index: 1000;
|
||||
max-height: 250px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.dropdown-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 6px;
|
||||
border-bottom: 1px solid var(--border-color, #333);
|
||||
}
|
||||
|
||||
.dropdown-actions button {
|
||||
flex: 1;
|
||||
padding: 4px 8px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
background: var(--bg-tertiary, #333);
|
||||
color: var(--text-secondary, #aaa);
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropdown-actions button:hover {
|
||||
background: var(--bg-hover, #444);
|
||||
color: var(--text-primary, #fff);
|
||||
}
|
||||
|
||||
.dropdown-list {
|
||||
overflow-y: auto;
|
||||
max-height: 200px;
|
||||
}
|
||||
|
||||
.dropdown-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 6px 8px;
|
||||
cursor: pointer;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.dropdown-item:hover {
|
||||
background: var(--bg-hover, #2a2a2a);
|
||||
}
|
||||
|
||||
.dropdown-item.selected {
|
||||
background: var(--accent-color-dim, rgba(0, 120, 212, 0.2));
|
||||
}
|
||||
|
||||
.layer-checkbox {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
accent-color: var(--accent-color, #0078d4);
|
||||
}
|
||||
|
||||
.layer-index {
|
||||
width: 20px;
|
||||
font-size: 10px;
|
||||
color: var(--text-tertiary, #666);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.layer-name {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
color: var(--text-primary, #fff);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CollisionLayerSelector;
|
||||
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* Collision Matrix Editor Component
|
||||
* 碰撞矩阵编辑器组件
|
||||
*
|
||||
* 用于配置物理层之间的碰撞关系,支持 16 个碰撞层。
|
||||
* 使用三角形矩阵布局,双击行标题可编辑层名称。
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { CollisionLayerConfig } from '../../services/CollisionLayerConfig';
|
||||
|
||||
interface CollisionMatrixEditorProps {
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export const CollisionMatrixEditor: React.FC<CollisionMatrixEditorProps> = ({ onClose }) => {
|
||||
const [layers, setLayers] = useState(CollisionLayerConfig.getInstance().getLayers());
|
||||
const [editingLayer, setEditingLayer] = useState<number | null>(null);
|
||||
const [editName, setEditName] = useState('');
|
||||
const [hoverCell, setHoverCell] = useState<{ row: number; col: number } | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const config = CollisionLayerConfig.getInstance();
|
||||
|
||||
useEffect(() => {
|
||||
const handleUpdate = () => {
|
||||
setLayers([...config.getLayers()]);
|
||||
};
|
||||
config.addListener(handleUpdate);
|
||||
return () => config.removeListener(handleUpdate);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingLayer !== null && inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
inputRef.current.select();
|
||||
}
|
||||
}, [editingLayer]);
|
||||
|
||||
const handleToggleCollision = useCallback((layerA: number, layerB: number) => {
|
||||
const canCollide = config.canLayersCollide(layerA, layerB);
|
||||
config.setLayersCanCollide(layerA, layerB, !canCollide);
|
||||
}, []);
|
||||
|
||||
const handleStartEdit = (index: number, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setEditingLayer(index);
|
||||
setEditName(layers[index]?.name ?? '');
|
||||
};
|
||||
|
||||
const handleSaveEdit = () => {
|
||||
if (editingLayer !== null && editName.trim()) {
|
||||
config.setLayerName(editingLayer, editName.trim());
|
||||
}
|
||||
setEditingLayer(null);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSaveEdit();
|
||||
} else if (e.key === 'Escape') {
|
||||
setEditingLayer(null);
|
||||
}
|
||||
};
|
||||
|
||||
const renderTriangleMatrix = () => {
|
||||
const visibleLayers = layers.slice(0, 16);
|
||||
|
||||
return (
|
||||
<div className="cmx-container">
|
||||
{/* 提示信息 */}
|
||||
<div className="cmx-hint">双击层名称可编辑</div>
|
||||
|
||||
<div className="cmx-matrix" onMouseLeave={() => setHoverCell(null)}>
|
||||
{/* 列标题 */}
|
||||
<div className="cmx-col-headers">
|
||||
{visibleLayers.map((layer, colIdx) => (
|
||||
<div
|
||||
key={colIdx}
|
||||
className={`cmx-col-label ${hoverCell?.col === colIdx ? 'highlight' : ''}`}
|
||||
style={{ left: `${72 + colIdx * 18}px` }}
|
||||
>
|
||||
<span className="cmx-col-text">{layer.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 矩阵行 */}
|
||||
<div className="cmx-rows">
|
||||
{visibleLayers.map((rowLayer, rowIdx) => (
|
||||
<div key={rowIdx} className={`cmx-row ${rowIdx % 2 === 0 ? 'even' : 'odd'}`}>
|
||||
{/* 行标题 */}
|
||||
<div
|
||||
className={`cmx-row-label ${hoverCell?.row === rowIdx ? 'highlight' : ''}`}
|
||||
onDoubleClick={(e) => handleStartEdit(rowIdx, e)}
|
||||
>
|
||||
{editingLayer === rowIdx ? (
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
onBlur={handleSaveEdit}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="cmx-edit-input"
|
||||
maxLength={16}
|
||||
/>
|
||||
) : (
|
||||
<span className="cmx-row-text">{rowLayer.name}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 单元格 */}
|
||||
<div className="cmx-cells">
|
||||
{visibleLayers.slice(0, rowIdx + 1).map((_, colIdx) => {
|
||||
const canCollide = config.canLayersCollide(rowIdx, colIdx);
|
||||
const isHovered = hoverCell?.row === rowIdx && hoverCell?.col === colIdx;
|
||||
const isHighlightRow = hoverCell?.row === rowIdx;
|
||||
const isHighlightCol = hoverCell?.col === colIdx;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={colIdx}
|
||||
className={`cmx-cell ${isHovered ? 'hovered' : ''} ${(isHighlightRow || isHighlightCol) && !isHovered ? 'highlight' : ''}`}
|
||||
onClick={() => handleToggleCollision(rowIdx, colIdx)}
|
||||
onMouseEnter={() => setHoverCell({ row: rowIdx, col: colIdx })}
|
||||
>
|
||||
<div className={`cmx-checkbox ${canCollide ? 'checked' : ''}`} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="cmx-editor">
|
||||
{renderTriangleMatrix()}
|
||||
|
||||
<style>{`
|
||||
.cmx-editor {
|
||||
font-size: 11px;
|
||||
color: var(--text-primary, #ccc);
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.cmx-container {
|
||||
position: relative;
|
||||
padding: 8px;
|
||||
padding-top: 75px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.cmx-hint {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 8px;
|
||||
font-size: 10px;
|
||||
color: var(--text-tertiary, #666);
|
||||
}
|
||||
|
||||
.cmx-matrix {
|
||||
position: relative;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* 列标题 */
|
||||
.cmx-col-headers {
|
||||
position: absolute;
|
||||
top: -65px;
|
||||
left: 0;
|
||||
height: 65px;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.cmx-col-label {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
width: 18px;
|
||||
height: 65px;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: flex-start;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.cmx-col-label.highlight .cmx-col-text {
|
||||
color: var(--accent-color, #58a6ff);
|
||||
}
|
||||
|
||||
.cmx-col-text {
|
||||
transform-origin: left bottom;
|
||||
transform: rotate(-45deg);
|
||||
white-space: nowrap;
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary, #8b8b8b);
|
||||
padding-left: 2px;
|
||||
}
|
||||
|
||||
/* 行 */
|
||||
.cmx-rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.cmx-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.cmx-row.even {
|
||||
background: rgba(255, 255, 255, 0.015);
|
||||
}
|
||||
|
||||
.cmx-row-label {
|
||||
width: 72px;
|
||||
min-width: 72px;
|
||||
padding-right: 8px;
|
||||
text-align: right;
|
||||
cursor: default;
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.cmx-row-label.highlight .cmx-row-text {
|
||||
color: var(--accent-color, #58a6ff);
|
||||
}
|
||||
|
||||
.cmx-row-text {
|
||||
font-size: 10px;
|
||||
color: var(--text-secondary, #8b8b8b);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.cmx-edit-input {
|
||||
width: 64px;
|
||||
padding: 1px 4px;
|
||||
border: 1px solid var(--accent-color, #58a6ff);
|
||||
border-radius: 2px;
|
||||
background: var(--input-bg, #1e1e1e);
|
||||
color: var(--text-primary, #ccc);
|
||||
font-size: 10px;
|
||||
outline: none;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* 单元格 */
|
||||
.cmx-cells {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.cmx-cell {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.cmx-cell:last-child {
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.cmx-cell.highlight {
|
||||
background: rgba(88, 166, 255, 0.06);
|
||||
}
|
||||
|
||||
.cmx-cell.hovered {
|
||||
background: rgba(88, 166, 255, 0.12);
|
||||
}
|
||||
|
||||
.cmx-checkbox {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 1px solid var(--border-color, #404040);
|
||||
border-radius: 2px;
|
||||
background: var(--input-bg, #1e1e1e);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.cmx-cell:hover .cmx-checkbox {
|
||||
border-color: var(--text-tertiary, #606060);
|
||||
}
|
||||
|
||||
.cmx-checkbox.checked {
|
||||
background: var(--accent-color, #58a6ff);
|
||||
border-color: var(--accent-color, #58a6ff);
|
||||
}
|
||||
|
||||
.cmx-checkbox.checked::after {
|
||||
content: '';
|
||||
display: block;
|
||||
width: 6px;
|
||||
height: 3px;
|
||||
border-left: 1.5px solid white;
|
||||
border-bottom: 1.5px solid white;
|
||||
transform: rotate(-45deg) translate(1px, 2px);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CollisionMatrixEditor;
|
||||
@@ -2,10 +2,8 @@
|
||||
* Physics 2D Gizmo Implementation
|
||||
* 2D 物理 Gizmo 实现
|
||||
*
|
||||
* Registers gizmo providers for physics components using the GizmoRegistry.
|
||||
* Rendered via Rust WebGL engine for optimal performance.
|
||||
* 使用 GizmoRegistry 为物理组件注册 gizmo 提供者。
|
||||
* 通过 Rust WebGL 引擎渲染以获得最佳性能。
|
||||
* 通过 Rust WebGL 引擎渲染。
|
||||
*/
|
||||
|
||||
import type { Entity } from '@esengine/ecs-framework';
|
||||
@@ -14,9 +12,10 @@ import type {
|
||||
IRectGizmoData,
|
||||
ICircleGizmoData,
|
||||
ILineGizmoData,
|
||||
ICapsuleGizmoData,
|
||||
GizmoColor
|
||||
} from '@esengine/editor-core';
|
||||
import { GizmoColors, GizmoRegistry } from '@esengine/editor-core';
|
||||
import { GizmoRegistry } from '@esengine/editor-core';
|
||||
import { TransformComponent } from '@esengine/ecs-components';
|
||||
|
||||
import { BoxCollider2DComponent } from '../../components/BoxCollider2DComponent';
|
||||
@@ -27,38 +26,77 @@ import { Rigidbody2DComponent } from '../../components/Rigidbody2DComponent';
|
||||
import { RigidbodyType2D } from '../../types/Physics2DTypes';
|
||||
|
||||
/**
|
||||
* Collider gizmo color based on selection state
|
||||
* 根据选择状态设置碰撞体 gizmo 颜色
|
||||
* 物理 Gizmo 颜色配置
|
||||
*/
|
||||
const PhysicsGizmoColors = {
|
||||
collider: { r: 0.0, g: 0.8, b: 0.0, a: 1.0 } as GizmoColor,
|
||||
trigger: { r: 1.0, g: 0.6, b: 0.0, a: 1.0 } as GizmoColor,
|
||||
selected: { r: 0.0, g: 1.0, b: 1.0, a: 1.0 } as GizmoColor,
|
||||
dynamicBody: { r: 0.2, g: 0.6, b: 1.0, a: 0.9 } as GizmoColor,
|
||||
kinematicBody: { r: 0.8, g: 0.3, b: 1.0, a: 0.9 } as GizmoColor,
|
||||
staticBody: { r: 0.5, g: 0.5, b: 0.5, a: 0.7 } as GizmoColor,
|
||||
velocity: { r: 1.0, g: 0.2, b: 0.2, a: 0.9 } as GizmoColor,
|
||||
centerMark: { r: 1.0, g: 1.0, b: 1.0, a: 0.8 } as GizmoColor,
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取碰撞体 Gizmo 颜色
|
||||
*/
|
||||
function getColliderColor(isSelected: boolean, isTrigger: boolean): GizmoColor {
|
||||
if (isTrigger) {
|
||||
return isSelected
|
||||
? { r: 1, g: 0.5, b: 0, a: 0.8 } // Orange for selected trigger
|
||||
: { r: 1, g: 0.5, b: 0, a: 0.4 }; // Semi-transparent orange for unselected trigger
|
||||
if (isSelected) {
|
||||
return PhysicsGizmoColors.selected;
|
||||
}
|
||||
return isSelected
|
||||
? GizmoColors.collider // Cyan for selected collider
|
||||
: { ...GizmoColors.collider, a: 0.4 }; // Semi-transparent cyan for unselected
|
||||
if (isTrigger) {
|
||||
return PhysicsGizmoColors.trigger;
|
||||
}
|
||||
return PhysicsGizmoColors.collider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigidbody indicator color based on body type
|
||||
* 根据刚体类型设置指示器颜色
|
||||
* 获取刚体类型颜色
|
||||
*/
|
||||
function getRigidbodyColor(bodyType: RigidbodyType2D, isSelected: boolean): GizmoColor {
|
||||
const alpha = isSelected ? 0.8 : 0.4;
|
||||
const baseAlpha = isSelected ? 1.0 : 0.7;
|
||||
|
||||
switch (bodyType) {
|
||||
case RigidbodyType2D.Dynamic:
|
||||
return { r: 0, g: 0.8, b: 1, a: alpha }; // Light blue for dynamic
|
||||
return { ...PhysicsGizmoColors.dynamicBody, a: baseAlpha };
|
||||
case RigidbodyType2D.Kinematic:
|
||||
return { r: 1, g: 0.8, b: 0, a: alpha }; // Yellow for kinematic
|
||||
return { ...PhysicsGizmoColors.kinematicBody, a: baseAlpha };
|
||||
case RigidbodyType2D.Static:
|
||||
return { r: 0.5, g: 0.5, b: 0.5, a: alpha }; // Gray for static
|
||||
return { ...PhysicsGizmoColors.staticBody, a: baseAlpha };
|
||||
default:
|
||||
return { r: 1, g: 1, b: 1, a: alpha };
|
||||
return { r: 1, g: 1, b: 1, a: baseAlpha };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建中心点标记 Gizmo (十字形)
|
||||
*/
|
||||
function createCenterMarkGizmo(x: number, y: number, size: number, color: GizmoColor): ILineGizmoData[] {
|
||||
const halfSize = size / 2;
|
||||
return [
|
||||
{
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: x - halfSize, y: y },
|
||||
{ x: x + halfSize, y: y }
|
||||
],
|
||||
color,
|
||||
closed: false
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: x, y: y - halfSize },
|
||||
{ x: x, y: y + halfSize }
|
||||
],
|
||||
color,
|
||||
closed: false
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* BoxCollider2D gizmo provider
|
||||
* 矩形碰撞体 gizmo 提供者
|
||||
@@ -74,22 +112,24 @@ function boxCollider2DGizmoProvider(
|
||||
const gizmos: IGizmoRenderData[] = [];
|
||||
const color = getColliderColor(isSelected, collider.isTrigger);
|
||||
|
||||
// Get rotation (handle both number and Vector3)
|
||||
const rotation = typeof transform.rotation === 'number'
|
||||
? transform.rotation
|
||||
: transform.rotation.z;
|
||||
|
||||
// Calculate world position with offset
|
||||
const worldX = transform.position.x + collider.offset.x * transform.scale.x;
|
||||
const worldY = transform.position.y + collider.offset.y * transform.scale.y;
|
||||
const scaledWidth = collider.width * transform.scale.x;
|
||||
const scaledHeight = collider.height * transform.scale.y;
|
||||
const totalRotation = rotation + collider.rotationOffset;
|
||||
|
||||
// 主要矩形边框
|
||||
const rectGizmo: IRectGizmoData = {
|
||||
type: 'rect',
|
||||
x: worldX,
|
||||
y: worldY,
|
||||
width: collider.width * transform.scale.x,
|
||||
height: collider.height * transform.scale.y,
|
||||
rotation: rotation + collider.rotationOffset,
|
||||
width: scaledWidth,
|
||||
height: scaledHeight,
|
||||
rotation: totalRotation,
|
||||
originX: 0.5,
|
||||
originY: 0.5,
|
||||
color,
|
||||
@@ -97,6 +137,12 @@ function boxCollider2DGizmoProvider(
|
||||
};
|
||||
gizmos.push(rectGizmo);
|
||||
|
||||
// 选中时显示中心点标记
|
||||
if (isSelected) {
|
||||
const centerMarkSize = Math.min(scaledWidth, scaledHeight) * 0.1;
|
||||
gizmos.push(...createCenterMarkGizmo(worldX, worldY, centerMarkSize, PhysicsGizmoColors.centerMark));
|
||||
}
|
||||
|
||||
return gizmos;
|
||||
}
|
||||
|
||||
@@ -115,22 +161,54 @@ function circleCollider2DGizmoProvider(
|
||||
const gizmos: IGizmoRenderData[] = [];
|
||||
const color = getColliderColor(isSelected, collider.isTrigger);
|
||||
|
||||
// Calculate world position with offset
|
||||
const worldX = transform.position.x + collider.offset.x * transform.scale.x;
|
||||
const worldY = transform.position.y + collider.offset.y * transform.scale.y;
|
||||
|
||||
// Use the larger scale for radius (circles should remain circular)
|
||||
const scale = Math.max(Math.abs(transform.scale.x), Math.abs(transform.scale.y));
|
||||
const scaledRadius = collider.radius * scale;
|
||||
|
||||
// 主要圆形边框
|
||||
const circleGizmo: ICircleGizmoData = {
|
||||
type: 'circle',
|
||||
x: worldX,
|
||||
y: worldY,
|
||||
radius: collider.radius * scale,
|
||||
radius: scaledRadius,
|
||||
color
|
||||
};
|
||||
gizmos.push(circleGizmo);
|
||||
|
||||
// 选中时显示额外信息
|
||||
if (isSelected) {
|
||||
// 中心点标记
|
||||
const centerMarkSize = scaledRadius * 0.15;
|
||||
gizmos.push(...createCenterMarkGizmo(worldX, worldY, centerMarkSize, PhysicsGizmoColors.centerMark));
|
||||
|
||||
// 半径指示线 (从中心到右边缘)
|
||||
const rotation = typeof transform.rotation === 'number'
|
||||
? transform.rotation
|
||||
: transform.rotation.z;
|
||||
const cos = Math.cos(rotation);
|
||||
const sin = Math.sin(rotation);
|
||||
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: worldX, y: worldY },
|
||||
{ x: worldX + scaledRadius * cos, y: worldY + scaledRadius * sin }
|
||||
],
|
||||
color: PhysicsGizmoColors.selected,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
|
||||
// 边缘小圆点
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: worldX + scaledRadius * cos,
|
||||
y: worldY + scaledRadius * sin,
|
||||
radius: scaledRadius * 0.08,
|
||||
color: PhysicsGizmoColors.selected
|
||||
} as ICircleGizmoData);
|
||||
}
|
||||
|
||||
return gizmos;
|
||||
}
|
||||
|
||||
@@ -149,73 +227,32 @@ function capsuleCollider2DGizmoProvider(
|
||||
const gizmos: IGizmoRenderData[] = [];
|
||||
const color = getColliderColor(isSelected, collider.isTrigger);
|
||||
|
||||
// Get rotation
|
||||
const rotation = typeof transform.rotation === 'number'
|
||||
? transform.rotation
|
||||
: transform.rotation.z;
|
||||
const totalRotation = rotation + collider.rotationOffset;
|
||||
|
||||
// Calculate world position with offset
|
||||
const worldX = transform.position.x + collider.offset.x * transform.scale.x;
|
||||
const worldY = transform.position.y + collider.offset.y * transform.scale.y;
|
||||
|
||||
const radius = collider.radius * transform.scale.x;
|
||||
const halfHeight = collider.halfHeight * transform.scale.y;
|
||||
|
||||
// Draw capsule as two circles and connecting lines
|
||||
// 绘制胶囊体为两个圆和连接线
|
||||
const cos = Math.cos(totalRotation);
|
||||
const sin = Math.sin(totalRotation);
|
||||
|
||||
// Top circle center
|
||||
const topCenterX = worldX - sin * halfHeight;
|
||||
const topCenterY = worldY + cos * halfHeight;
|
||||
|
||||
// Bottom circle center
|
||||
const bottomCenterX = worldX + sin * halfHeight;
|
||||
const bottomCenterY = worldY - cos * halfHeight;
|
||||
|
||||
// Top semicircle
|
||||
// 使用原生胶囊 Gizmo 类型
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: topCenterX,
|
||||
y: topCenterY,
|
||||
type: 'capsule',
|
||||
x: worldX,
|
||||
y: worldY,
|
||||
radius,
|
||||
halfHeight,
|
||||
rotation: totalRotation,
|
||||
color
|
||||
} as ICircleGizmoData);
|
||||
} as ICapsuleGizmoData);
|
||||
|
||||
// Bottom semicircle
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: bottomCenterX,
|
||||
y: bottomCenterY,
|
||||
radius,
|
||||
color
|
||||
} as ICircleGizmoData);
|
||||
|
||||
// Connecting lines (left and right sides)
|
||||
const perpX = cos * radius;
|
||||
const perpY = sin * radius;
|
||||
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: topCenterX - perpX, y: topCenterY - perpY },
|
||||
{ x: bottomCenterX - perpX, y: bottomCenterY - perpY }
|
||||
],
|
||||
color,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: topCenterX + perpX, y: topCenterY + perpY },
|
||||
{ x: bottomCenterX + perpX, y: bottomCenterY + perpY }
|
||||
],
|
||||
color,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
if (isSelected) {
|
||||
const centerMarkSize = radius * 0.15;
|
||||
gizmos.push(...createCenterMarkGizmo(worldX, worldY, centerMarkSize, PhysicsGizmoColors.centerMark));
|
||||
}
|
||||
|
||||
return gizmos;
|
||||
}
|
||||
@@ -237,7 +274,6 @@ function polygonCollider2DGizmoProvider(
|
||||
const gizmos: IGizmoRenderData[] = [];
|
||||
const color = getColliderColor(isSelected, collider.isTrigger);
|
||||
|
||||
// Get rotation
|
||||
const rotation = typeof transform.rotation === 'number'
|
||||
? transform.rotation
|
||||
: transform.rotation.z;
|
||||
@@ -245,20 +281,17 @@ function polygonCollider2DGizmoProvider(
|
||||
const cos = Math.cos(totalRotation);
|
||||
const sin = Math.sin(totalRotation);
|
||||
|
||||
// Transform vertices to world space
|
||||
const worldPoints = collider.vertices.map(v => {
|
||||
// Apply scale
|
||||
const scaledX = (v.x + collider.offset.x) * transform.scale.x;
|
||||
const scaledY = (v.y + collider.offset.y) * transform.scale.y;
|
||||
const worldX = transform.position.x + collider.offset.x * transform.scale.x;
|
||||
const worldY = transform.position.y + collider.offset.y * transform.scale.y;
|
||||
|
||||
// Apply rotation
|
||||
const worldPoints = collider.vertices.map(v => {
|
||||
const scaledX = v.x * transform.scale.x;
|
||||
const scaledY = v.y * transform.scale.y;
|
||||
const rotatedX = scaledX * cos - scaledY * sin;
|
||||
const rotatedY = scaledX * sin + scaledY * cos;
|
||||
|
||||
// Apply translation
|
||||
return {
|
||||
x: transform.position.x + rotatedX,
|
||||
y: transform.position.y + rotatedY
|
||||
x: worldX + rotatedX,
|
||||
y: worldY + rotatedY
|
||||
};
|
||||
});
|
||||
|
||||
@@ -269,12 +302,30 @@ function polygonCollider2DGizmoProvider(
|
||||
closed: true
|
||||
} as ILineGizmoData);
|
||||
|
||||
if (isSelected) {
|
||||
// 中心点标记
|
||||
const centerMarkSize = 0.5;
|
||||
gizmos.push(...createCenterMarkGizmo(worldX, worldY, centerMarkSize, PhysicsGizmoColors.centerMark));
|
||||
|
||||
// 顶点标记
|
||||
const vertexSize = 0.15;
|
||||
for (const point of worldPoints) {
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
radius: vertexSize,
|
||||
color: PhysicsGizmoColors.selected
|
||||
} as ICircleGizmoData);
|
||||
}
|
||||
}
|
||||
|
||||
return gizmos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigidbody2D gizmo provider - shows velocity indicator when playing
|
||||
* 刚体 gizmo 提供者 - 播放时显示速度指示器
|
||||
* Rigidbody2D gizmo provider
|
||||
* 刚体 gizmo 提供者
|
||||
*/
|
||||
function rigidbody2DGizmoProvider(
|
||||
rigidbody: Rigidbody2DComponent,
|
||||
@@ -285,42 +336,71 @@ function rigidbody2DGizmoProvider(
|
||||
if (!transform) return [];
|
||||
|
||||
const gizmos: IGizmoRenderData[] = [];
|
||||
const bodyColor = getRigidbodyColor(rigidbody.bodyType, isSelected);
|
||||
|
||||
// Only show velocity indicator when selected and has significant velocity
|
||||
if (isSelected) {
|
||||
// 刚体类型标记
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: transform.position.x,
|
||||
y: transform.position.y,
|
||||
radius: 0.3,
|
||||
color: bodyColor
|
||||
} as ICircleGizmoData);
|
||||
|
||||
// 速度向量
|
||||
const velMagnitude = Math.sqrt(
|
||||
rigidbody.velocity.x * rigidbody.velocity.x +
|
||||
rigidbody.velocity.y * rigidbody.velocity.y
|
||||
);
|
||||
|
||||
// Draw velocity indicator if moving
|
||||
if (velMagnitude > 0.1) {
|
||||
const color = getRigidbodyColor(rigidbody.bodyType, isSelected);
|
||||
const scale = 0.5; // Scale factor for velocity visualization
|
||||
const scale = 0.5;
|
||||
const endX = transform.position.x + rigidbody.velocity.x * scale;
|
||||
const endY = transform.position.y + rigidbody.velocity.y * scale;
|
||||
|
||||
// 速度线
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: transform.position.x, y: transform.position.y },
|
||||
{ x: endX, y: endY }
|
||||
],
|
||||
color: PhysicsGizmoColors.velocity,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
|
||||
// 箭头
|
||||
const arrowSize = 0.3;
|
||||
const angle = Math.atan2(rigidbody.velocity.y, rigidbody.velocity.x);
|
||||
const arrowAngle = Math.PI / 6;
|
||||
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: endX, y: endY },
|
||||
{
|
||||
x: transform.position.x + rigidbody.velocity.x * scale,
|
||||
y: transform.position.y + rigidbody.velocity.y * scale
|
||||
x: endX - arrowSize * Math.cos(angle - arrowAngle),
|
||||
y: endY - arrowSize * Math.sin(angle - arrowAngle)
|
||||
}
|
||||
],
|
||||
color,
|
||||
color: PhysicsGizmoColors.velocity,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
|
||||
gizmos.push({
|
||||
type: 'line',
|
||||
points: [
|
||||
{ x: endX, y: endY },
|
||||
{
|
||||
x: endX - arrowSize * Math.cos(angle + arrowAngle),
|
||||
y: endY - arrowSize * Math.sin(angle + arrowAngle)
|
||||
}
|
||||
],
|
||||
color: PhysicsGizmoColors.velocity,
|
||||
closed: false
|
||||
} as ILineGizmoData);
|
||||
}
|
||||
|
||||
// Show body type indicator as small marker
|
||||
const markerColor = getRigidbodyColor(rigidbody.bodyType, true);
|
||||
gizmos.push({
|
||||
type: 'circle',
|
||||
x: transform.position.x,
|
||||
y: transform.position.y,
|
||||
radius: 0.1,
|
||||
color: markerColor
|
||||
} as ICircleGizmoData);
|
||||
}
|
||||
|
||||
return gizmos;
|
||||
|
||||
@@ -13,8 +13,10 @@ import type {
|
||||
import {
|
||||
EntityStoreService,
|
||||
MessageHub,
|
||||
ComponentRegistry
|
||||
ComponentRegistry,
|
||||
SettingsRegistry
|
||||
} from '@esengine/editor-core';
|
||||
import { DEFAULT_PHYSICS_CONFIG } from '../types/Physics2DTypes';
|
||||
import { TransformComponent } from '@esengine/ecs-components';
|
||||
|
||||
// Local imports
|
||||
@@ -24,15 +26,24 @@ import { CircleCollider2DComponent } from '../components/CircleCollider2DCompone
|
||||
import { CapsuleCollider2DComponent } from '../components/CapsuleCollider2DComponent';
|
||||
import { PolygonCollider2DComponent } from '../components/PolygonCollider2DComponent';
|
||||
import { registerPhysics2DGizmos } from './gizmos/Physics2DGizmo';
|
||||
import { Physics2DSystem } from '../systems/Physics2DSystem';
|
||||
import { CollisionMatrixEditor } from './components/CollisionMatrixEditor';
|
||||
|
||||
/**
|
||||
* Physics 2D Editor Module
|
||||
* 2D 物理编辑器模块
|
||||
*/
|
||||
export class Physics2DEditorModule implements IEditorModuleLoader {
|
||||
private settingsListener: ((event: Event) => void) | null = null;
|
||||
|
||||
async install(services: ServiceContainer): Promise<void> {
|
||||
// 注册物理设置到设置面板
|
||||
this.registerPhysicsSettings(services);
|
||||
|
||||
// 监听设置变更
|
||||
this.setupSettingsListener();
|
||||
|
||||
// 注册组件到编辑器组件注册表
|
||||
// 组件检视器现在通过 @Property 装饰器自动生成
|
||||
const componentRegistry = services.resolve(ComponentRegistry);
|
||||
if (componentRegistry) {
|
||||
componentRegistry.register({
|
||||
@@ -81,7 +92,193 @@ export class Physics2DEditorModule implements IEditorModuleLoader {
|
||||
}
|
||||
|
||||
async uninstall(): Promise<void> {
|
||||
// 清理资源
|
||||
// 移除设置监听器
|
||||
if (this.settingsListener) {
|
||||
window.removeEventListener('settings:changed', this.settingsListener);
|
||||
this.settingsListener = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置变更监听器
|
||||
*/
|
||||
private setupSettingsListener(): void {
|
||||
this.settingsListener = ((event: CustomEvent) => {
|
||||
const changedSettings = event.detail;
|
||||
|
||||
// 检查是否有物理相关设置变更
|
||||
const physicsKeys = Object.keys(changedSettings).filter(k => k.startsWith('physics.'));
|
||||
if (physicsKeys.length === 0) return;
|
||||
|
||||
this.applyPhysicsSettings(changedSettings);
|
||||
}) as EventListener;
|
||||
|
||||
window.addEventListener('settings:changed', this.settingsListener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用物理设置到物理系统
|
||||
*/
|
||||
private applyPhysicsSettings(settings: Record<string, unknown>): void {
|
||||
const scene = Core.scene;
|
||||
if (!scene) return;
|
||||
|
||||
const physicsSystem = scene.getSystem(Physics2DSystem);
|
||||
if (!physicsSystem) return;
|
||||
|
||||
const world = physicsSystem.world;
|
||||
if (!world) return;
|
||||
|
||||
// 构建配置对象
|
||||
const gravityX = settings['physics.gravity.x'] as number | undefined;
|
||||
const gravityY = settings['physics.gravity.y'] as number | undefined;
|
||||
|
||||
if (gravityX !== undefined || gravityY !== undefined) {
|
||||
const currentGravity = world.getGravity();
|
||||
world.updateConfig({
|
||||
gravity: {
|
||||
x: gravityX ?? currentGravity.x,
|
||||
y: gravityY ?? currentGravity.y
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (settings['physics.timestep'] !== undefined) {
|
||||
world.updateConfig({ timestep: settings['physics.timestep'] as number });
|
||||
}
|
||||
|
||||
if (settings['physics.maxSubsteps'] !== undefined) {
|
||||
world.updateConfig({ maxSubsteps: settings['physics.maxSubsteps'] as number });
|
||||
}
|
||||
|
||||
if (settings['physics.velocityIterations'] !== undefined) {
|
||||
world.updateConfig({ velocityIterations: settings['physics.velocityIterations'] as number });
|
||||
}
|
||||
|
||||
if (settings['physics.positionIterations'] !== undefined) {
|
||||
world.updateConfig({ positionIterations: settings['physics.positionIterations'] as number });
|
||||
}
|
||||
|
||||
if (settings['physics.allowSleep'] !== undefined) {
|
||||
world.updateConfig({ allowSleep: settings['physics.allowSleep'] as boolean });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册物理设置到设置面板
|
||||
*/
|
||||
private registerPhysicsSettings(services: ServiceContainer): void {
|
||||
const settingsRegistry = services.tryResolve(SettingsRegistry);
|
||||
if (!settingsRegistry) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRegistry.registerCategory({
|
||||
id: 'physics',
|
||||
title: '物理',
|
||||
description: '2D 物理引擎配置',
|
||||
sections: [
|
||||
{
|
||||
id: 'physics-world',
|
||||
title: '物理世界',
|
||||
description: '配置物理世界的基础参数',
|
||||
settings: [
|
||||
{
|
||||
key: 'physics.gravity.x',
|
||||
label: '重力 X',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.gravity.x,
|
||||
description: '水平方向重力(通常为 0)',
|
||||
step: 0.1
|
||||
},
|
||||
{
|
||||
key: 'physics.gravity.y',
|
||||
label: '重力 Y',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.gravity.y,
|
||||
description: '垂直方向重力(负值向下)',
|
||||
step: 0.1
|
||||
},
|
||||
{
|
||||
key: 'physics.timestep',
|
||||
label: '时间步长',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.timestep,
|
||||
description: '固定物理更新时间步长(秒)',
|
||||
min: 0.001,
|
||||
max: 0.1,
|
||||
step: 0.001
|
||||
},
|
||||
{
|
||||
key: 'physics.maxSubsteps',
|
||||
label: '最大子步数',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.maxSubsteps,
|
||||
description: '每帧最大物理子步数',
|
||||
min: 1,
|
||||
max: 32,
|
||||
step: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'physics-solver',
|
||||
title: '求解器',
|
||||
description: '配置物理求解器参数',
|
||||
settings: [
|
||||
{
|
||||
key: 'physics.velocityIterations',
|
||||
label: '速度迭代次数',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.velocityIterations,
|
||||
description: '速度求解器迭代次数,越高越精确但性能开销越大',
|
||||
min: 1,
|
||||
max: 16,
|
||||
step: 1
|
||||
},
|
||||
{
|
||||
key: 'physics.positionIterations',
|
||||
label: '位置迭代次数',
|
||||
type: 'number',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.positionIterations,
|
||||
description: '位置求解器迭代次数,越高越精确但性能开销越大',
|
||||
min: 1,
|
||||
max: 16,
|
||||
step: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'physics-behavior',
|
||||
title: '行为',
|
||||
description: '配置物理行为',
|
||||
settings: [
|
||||
{
|
||||
key: 'physics.allowSleep',
|
||||
label: '允许休眠',
|
||||
type: 'boolean',
|
||||
defaultValue: DEFAULT_PHYSICS_CONFIG.allowSleep,
|
||||
description: '允许静止的刚体进入休眠状态以提高性能'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'physics-collision',
|
||||
title: '碰撞层',
|
||||
description: '配置碰撞层和碰撞矩阵',
|
||||
settings: [
|
||||
{
|
||||
key: 'physics.collisionMatrix',
|
||||
label: '碰撞矩阵',
|
||||
type: 'collisionMatrix',
|
||||
defaultValue: null,
|
||||
description: '配置哪些层之间可以发生碰撞',
|
||||
customRenderer: CollisionMatrixEditor
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
getInspectorProviders() {
|
||||
|
||||
245
packages/physics-rapier2d/src/services/CollisionLayerConfig.ts
Normal file
245
packages/physics-rapier2d/src/services/CollisionLayerConfig.ts
Normal file
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Collision Layer Configuration Service
|
||||
* 碰撞层配置服务
|
||||
*
|
||||
* 管理碰撞层的定义和碰撞矩阵配置
|
||||
*/
|
||||
|
||||
/**
|
||||
* 碰撞层定义
|
||||
*/
|
||||
export interface CollisionLayerDefinition {
|
||||
/** 层索引 (0-15) */
|
||||
index: number;
|
||||
/** 层名称 */
|
||||
name: string;
|
||||
/** 层描述 */
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 碰撞层配置
|
||||
*/
|
||||
export interface CollisionLayerSettings {
|
||||
/** 层定义列表 */
|
||||
layers: CollisionLayerDefinition[];
|
||||
/** 碰撞矩阵 (16x16 位图,matrix[i] 表示第 i 层可以与哪些层碰撞) */
|
||||
collisionMatrix: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认碰撞层配置
|
||||
*/
|
||||
export const DEFAULT_COLLISION_LAYERS: CollisionLayerDefinition[] = [
|
||||
{ index: 0, name: 'Default', description: '默认层' },
|
||||
{ index: 1, name: 'Player', description: '玩家' },
|
||||
{ index: 2, name: 'Enemy', description: '敌人' },
|
||||
{ index: 3, name: 'Projectile', description: '投射物' },
|
||||
{ index: 4, name: 'Ground', description: '地面' },
|
||||
{ index: 5, name: 'Platform', description: '平台' },
|
||||
{ index: 6, name: 'Trigger', description: '触发器' },
|
||||
{ index: 7, name: 'Item', description: '物品' },
|
||||
{ index: 8, name: 'Layer8', description: '自定义层8' },
|
||||
{ index: 9, name: 'Layer9', description: '自定义层9' },
|
||||
{ index: 10, name: 'Layer10', description: '自定义层10' },
|
||||
{ index: 11, name: 'Layer11', description: '自定义层11' },
|
||||
{ index: 12, name: 'Layer12', description: '自定义层12' },
|
||||
{ index: 13, name: 'Layer13', description: '自定义层13' },
|
||||
{ index: 14, name: 'Layer14', description: '自定义层14' },
|
||||
{ index: 15, name: 'Layer15', description: '自定义层15' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 默认碰撞矩阵 - 所有层都可以互相碰撞
|
||||
*/
|
||||
export const DEFAULT_COLLISION_MATRIX: number[] = Array(16).fill(0xFFFF);
|
||||
|
||||
/**
|
||||
* 碰撞层配置管理器
|
||||
*/
|
||||
export class CollisionLayerConfig {
|
||||
private static instance: CollisionLayerConfig | null = null;
|
||||
|
||||
private layers: CollisionLayerDefinition[] = [...DEFAULT_COLLISION_LAYERS];
|
||||
private collisionMatrix: number[] = [...DEFAULT_COLLISION_MATRIX];
|
||||
private listeners: Set<() => void> = new Set();
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): CollisionLayerConfig {
|
||||
if (!CollisionLayerConfig.instance) {
|
||||
CollisionLayerConfig.instance = new CollisionLayerConfig();
|
||||
}
|
||||
return CollisionLayerConfig.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有层定义
|
||||
*/
|
||||
public getLayers(): readonly CollisionLayerDefinition[] {
|
||||
return this.layers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取层名称
|
||||
*/
|
||||
public getLayerName(index: number): string {
|
||||
if (index < 0 || index >= 16) return `Layer${index}`;
|
||||
return this.layers[index]?.name ?? `Layer${index}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置层名称
|
||||
*/
|
||||
public setLayerName(index: number, name: string): void {
|
||||
if (index < 0 || index >= 16) return;
|
||||
if (this.layers[index]) {
|
||||
this.layers[index].name = name;
|
||||
this.notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置层描述
|
||||
*/
|
||||
public setLayerDescription(index: number, description: string): void {
|
||||
if (index < 0 || index >= 16) return;
|
||||
if (this.layers[index]) {
|
||||
this.layers[index].description = description;
|
||||
this.notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取碰撞矩阵
|
||||
*/
|
||||
public getCollisionMatrix(): readonly number[] {
|
||||
return this.collisionMatrix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查两个层是否可以碰撞
|
||||
*/
|
||||
public canLayersCollide(layerA: number, layerB: number): boolean {
|
||||
if (layerA < 0 || layerA >= 16 || layerB < 0 || layerB >= 16) {
|
||||
return false;
|
||||
}
|
||||
return (this.collisionMatrix[layerA] & (1 << layerB)) !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置两个层是否可以碰撞
|
||||
*/
|
||||
public setLayersCanCollide(layerA: number, layerB: number, canCollide: boolean): void {
|
||||
if (layerA < 0 || layerA >= 16 || layerB < 0 || layerB >= 16) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (canCollide) {
|
||||
this.collisionMatrix[layerA] |= (1 << layerB);
|
||||
this.collisionMatrix[layerB] |= (1 << layerA);
|
||||
} else {
|
||||
this.collisionMatrix[layerA] &= ~(1 << layerB);
|
||||
this.collisionMatrix[layerB] &= ~(1 << layerA);
|
||||
}
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定层的碰撞掩码
|
||||
*/
|
||||
public getLayerMask(layerIndex: number): number {
|
||||
if (layerIndex < 0 || layerIndex >= 16) return 0xFFFF;
|
||||
return this.collisionMatrix[layerIndex];
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据层索引获取层位值
|
||||
*/
|
||||
public getLayerBit(layerIndex: number): number {
|
||||
if (layerIndex < 0 || layerIndex >= 16) return 1;
|
||||
return 1 << layerIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从层位值获取层索引
|
||||
*/
|
||||
public getLayerIndex(layerBit: number): number {
|
||||
for (let i = 0; i < 16; i++) {
|
||||
if (layerBit === (1 << i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
// 如果是多层位值,返回第一个设置的位
|
||||
for (let i = 0; i < 16; i++) {
|
||||
if ((layerBit & (1 << i)) !== 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载配置
|
||||
*/
|
||||
public loadSettings(settings: Partial<CollisionLayerSettings>): void {
|
||||
if (settings.layers) {
|
||||
this.layers = settings.layers.map((layer, i) => ({
|
||||
index: layer.index ?? i,
|
||||
name: layer.name ?? `Layer${i}`,
|
||||
description: layer.description
|
||||
}));
|
||||
// 确保有16个层
|
||||
while (this.layers.length < 16) {
|
||||
const idx = this.layers.length;
|
||||
this.layers.push({ index: idx, name: `Layer${idx}` });
|
||||
}
|
||||
}
|
||||
if (settings.collisionMatrix) {
|
||||
this.collisionMatrix = [...settings.collisionMatrix];
|
||||
while (this.collisionMatrix.length < 16) {
|
||||
this.collisionMatrix.push(0xFFFF);
|
||||
}
|
||||
}
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出配置
|
||||
*/
|
||||
public exportSettings(): CollisionLayerSettings {
|
||||
return {
|
||||
layers: [...this.layers],
|
||||
collisionMatrix: [...this.collisionMatrix]
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置为默认配置
|
||||
*/
|
||||
public resetToDefault(): void {
|
||||
this.layers = [...DEFAULT_COLLISION_LAYERS];
|
||||
this.collisionMatrix = [...DEFAULT_COLLISION_MATRIX];
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加监听器
|
||||
*/
|
||||
public addListener(listener: () => void): void {
|
||||
this.listeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除监听器
|
||||
*/
|
||||
public removeListener(listener: () => void): void {
|
||||
this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private notifyListeners(): void {
|
||||
for (const listener of this.listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,12 @@
|
||||
*/
|
||||
|
||||
export { Physics2DService } from './Physics2DService';
|
||||
export {
|
||||
CollisionLayerConfig,
|
||||
DEFAULT_COLLISION_LAYERS,
|
||||
DEFAULT_COLLISION_MATRIX
|
||||
} from './CollisionLayerConfig';
|
||||
export type {
|
||||
CollisionLayerDefinition,
|
||||
CollisionLayerSettings
|
||||
} from './CollisionLayerConfig';
|
||||
|
||||
@@ -314,9 +314,10 @@ export class Physics2DSystem extends EntitySystem {
|
||||
// 收集并创建碰撞体
|
||||
const colliderHandles: number[] = [];
|
||||
const colliders = this._getColliders(entity);
|
||||
const scale: Vector2 = { x: transform.scale.x, y: transform.scale.y };
|
||||
|
||||
for (const collider of colliders) {
|
||||
const colliderHandle = this._world.createCollider(entity.id, collider, bodyHandle);
|
||||
const colliderHandle = this._world.createCollider(entity.id, collider, bodyHandle, scale);
|
||||
if (colliderHandle !== null) {
|
||||
colliderHandles.push(colliderHandle);
|
||||
}
|
||||
@@ -379,6 +380,7 @@ export class Physics2DSystem extends EntitySystem {
|
||||
|
||||
// 检查碰撞体是否需要重建
|
||||
const colliders = this._getColliders(entity);
|
||||
const scale: Vector2 = { x: transform.scale.x, y: transform.scale.y };
|
||||
for (const collider of colliders) {
|
||||
if (collider._needsRebuild) {
|
||||
// 移除旧碰撞体
|
||||
@@ -391,7 +393,7 @@ export class Physics2DSystem extends EntitySystem {
|
||||
}
|
||||
|
||||
// 创建新碰撞体
|
||||
const newHandle = this._world.createCollider(entity.id, collider, mapping.bodyHandle);
|
||||
const newHandle = this._world.createCollider(entity.id, collider, mapping.bodyHandle, scale);
|
||||
if (newHandle !== null) {
|
||||
mapping.colliderHandles.push(newHandle);
|
||||
}
|
||||
|
||||
@@ -480,12 +480,13 @@ export class Physics2DWorld {
|
||||
* @param entityId 实体 ID
|
||||
* @param collider 碰撞体组件
|
||||
* @param bodyHandle 关联的刚体句柄(可选)
|
||||
* @param scale Transform 的缩放值(可选)
|
||||
*/
|
||||
public createCollider(entityId: number, collider: Collider2DBase, bodyHandle?: number): number | null {
|
||||
public createCollider(entityId: number, collider: Collider2DBase, bodyHandle?: number, scale?: Vector2): number | null {
|
||||
if (!this._world || !this._rapier) return null;
|
||||
|
||||
// 创建碰撞体描述
|
||||
const colliderDesc = this._createColliderDesc(collider);
|
||||
const colliderDesc = this._createColliderDesc(collider, scale);
|
||||
if (!colliderDesc) return null;
|
||||
|
||||
// 创建碰撞体
|
||||
@@ -508,6 +509,83 @@ export class Physics2DWorld {
|
||||
return handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建静态碰撞体(不需要刚体)
|
||||
* 用于 Tilemap 等静态碰撞场景
|
||||
*
|
||||
* @param entityId 实体 ID
|
||||
* @param position 碰撞体中心位置
|
||||
* @param halfExtents 半宽高
|
||||
* @param collisionLayer 碰撞层
|
||||
* @param collisionMask 碰撞掩码
|
||||
* @param friction 摩擦系数
|
||||
* @param restitution 弹性系数
|
||||
* @param isTrigger 是否为触发器
|
||||
*/
|
||||
public createStaticCollider(
|
||||
entityId: number,
|
||||
position: Vector2,
|
||||
halfExtents: Vector2,
|
||||
collisionLayer: number,
|
||||
collisionMask: number,
|
||||
friction: number,
|
||||
restitution: number,
|
||||
isTrigger: boolean
|
||||
): number | null {
|
||||
if (!this._world || !this._rapier) return null;
|
||||
|
||||
// 创建固定刚体(用于静态碰撞体)
|
||||
const bodyDesc = this._rapier.RigidBodyDesc.fixed()
|
||||
.setTranslation(position.x, position.y);
|
||||
const body = this._world.createRigidBody(bodyDesc);
|
||||
|
||||
// 创建碰撞体描述
|
||||
const colliderDesc = this._rapier.ColliderDesc.cuboid(halfExtents.x, halfExtents.y)
|
||||
.setFriction(friction)
|
||||
.setRestitution(restitution)
|
||||
.setSensor(isTrigger)
|
||||
.setCollisionGroups(this._createCollisionGroups(collisionLayer, collisionMask))
|
||||
.setActiveEvents(this._rapier.ActiveEvents.COLLISION_EVENTS);
|
||||
|
||||
// 创建碰撞体
|
||||
const collider = this._world.createCollider(colliderDesc, body);
|
||||
const handle = collider.handle;
|
||||
|
||||
// 创建虚拟的碰撞体映射(用于事件处理)
|
||||
// 注意:这里我们没有实际的 Collider2DBase 组件
|
||||
const dummyCollider = {
|
||||
_colliderHandle: handle,
|
||||
_attachedBodyEntityId: null,
|
||||
_needsRebuild: false,
|
||||
isTrigger,
|
||||
collisionLayer,
|
||||
collisionMask,
|
||||
friction,
|
||||
restitution,
|
||||
density: 1,
|
||||
offset: { x: 0, y: 0 },
|
||||
rotationOffset: 0,
|
||||
getShapeType: () => 'box',
|
||||
calculateArea: () => halfExtents.x * halfExtents.y * 4,
|
||||
calculateAABB: () => ({
|
||||
min: { x: position.x - halfExtents.x, y: position.y - halfExtents.y },
|
||||
max: { x: position.x + halfExtents.x, y: position.y + halfExtents.y }
|
||||
}),
|
||||
setLayer: () => {},
|
||||
addLayer: () => {},
|
||||
removeLayer: () => {},
|
||||
isInLayer: () => false,
|
||||
setCollisionMask: () => {},
|
||||
canCollideWith: () => true,
|
||||
markNeedsRebuild: () => {},
|
||||
onRemovedFromEntity: () => {},
|
||||
} as unknown as Collider2DBase;
|
||||
|
||||
this._colliderMap.set(handle, { entityId, colliderComponent: dummyCollider });
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除碰撞体
|
||||
* @param handle 碰撞体句柄
|
||||
@@ -790,6 +868,30 @@ export class Physics2DWorld {
|
||||
return this._config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新物理配置
|
||||
*/
|
||||
public updateConfig(config: Partial<Physics2DConfig>): void {
|
||||
if (config.gravity !== undefined) {
|
||||
this.setGravity(config.gravity);
|
||||
}
|
||||
if (config.timestep !== undefined) {
|
||||
this._config.timestep = config.timestep;
|
||||
}
|
||||
if (config.maxSubsteps !== undefined) {
|
||||
this._config.maxSubsteps = config.maxSubsteps;
|
||||
}
|
||||
if (config.velocityIterations !== undefined) {
|
||||
this._config.velocityIterations = config.velocityIterations;
|
||||
}
|
||||
if (config.positionIterations !== undefined) {
|
||||
this._config.positionIterations = config.positionIterations;
|
||||
}
|
||||
if (config.allowSleep !== undefined) {
|
||||
this._config.allowSleep = config.allowSleep;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取状态
|
||||
*/
|
||||
@@ -869,34 +971,37 @@ export class Physics2DWorld {
|
||||
/**
|
||||
* 创建碰撞体描述
|
||||
*/
|
||||
private _createColliderDesc(collider: Collider2DBase): RAPIER.ColliderDesc | null {
|
||||
private _createColliderDesc(collider: Collider2DBase, scale?: Vector2): RAPIER.ColliderDesc | null {
|
||||
if (!this._rapier) return null;
|
||||
|
||||
const sx = scale?.x ?? 1;
|
||||
const sy = scale?.y ?? 1;
|
||||
const shapeType = collider.getShapeType();
|
||||
let colliderDesc: RAPIER.ColliderDesc | null = null;
|
||||
|
||||
switch (shapeType) {
|
||||
case 'box': {
|
||||
const box = collider as BoxCollider2DComponent;
|
||||
colliderDesc = this._rapier.ColliderDesc.cuboid(box.halfWidth, box.halfHeight);
|
||||
colliderDesc = this._rapier.ColliderDesc.cuboid(box.halfWidth * sx, box.halfHeight * sy);
|
||||
break;
|
||||
}
|
||||
case 'circle': {
|
||||
const circle = collider as CircleCollider2DComponent;
|
||||
colliderDesc = this._rapier.ColliderDesc.ball(circle.radius);
|
||||
const uniformScale = Math.max(Math.abs(sx), Math.abs(sy));
|
||||
colliderDesc = this._rapier.ColliderDesc.ball(circle.radius * uniformScale);
|
||||
break;
|
||||
}
|
||||
case 'capsule': {
|
||||
const capsule = collider as CapsuleCollider2DComponent;
|
||||
colliderDesc = this._rapier.ColliderDesc.capsule(capsule.halfHeight, capsule.radius);
|
||||
colliderDesc = this._rapier.ColliderDesc.capsule(capsule.halfHeight * sy, capsule.radius * sx);
|
||||
break;
|
||||
}
|
||||
case 'polygon': {
|
||||
const polygon = collider as PolygonCollider2DComponent;
|
||||
const vertices = new Float32Array(polygon.vertices.length * 2);
|
||||
for (let i = 0; i < polygon.vertices.length; i++) {
|
||||
vertices[i * 2] = polygon.vertices[i].x;
|
||||
vertices[i * 2 + 1] = polygon.vertices[i].y;
|
||||
vertices[i * 2] = polygon.vertices[i].x * sx;
|
||||
vertices[i * 2 + 1] = polygon.vertices[i].y * sy;
|
||||
}
|
||||
colliderDesc = this._rapier.ColliderDesc.convexHull(vertices);
|
||||
break;
|
||||
@@ -910,7 +1015,7 @@ export class Physics2DWorld {
|
||||
|
||||
// 配置碰撞体属性
|
||||
colliderDesc
|
||||
.setTranslation(collider.offset.x, collider.offset.y)
|
||||
.setTranslation(collider.offset.x * sx, collider.offset.y * sy)
|
||||
.setRotation(collider.rotationOffset)
|
||||
.setFriction(collider.friction)
|
||||
.setRestitution(collider.restitution)
|
||||
|
||||
Reference in New Issue
Block a user