效果大概是这样的,
线上面加的是BoxCollider2D
代码如下:
import { _decorator, Component, Node, Graphics, GraphicsComponent, input, Input, log, EventTouch, Color, Camera, View, Vec3, CameraComponent, CCObject, Vec2, RigidBody2D, BoxCollider2D, PhysicsSystem2D, EPhysics2DDrawFlags, labelAssembler, math, ERaycast2DType, ERigidBody2DType, Quat, Mat4, v3, mat4, physics, Mat3, quat, v2, PolygonCollider2D } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('MainScene')
export class MainScene extends Component {
@property(GraphicsComponent)
graph: Graphics = null;
@property(CameraComponent)
camera: Camera
points: Array<Vec3> = new Array<Vec3>();
private r2dList: RigidBody2D[] = [];
onLoad() {
// this.graph.node.getComponent(BoxCollider2D).size = math.size(1000,20);
PhysicsSystem2D.instance.enable = true;
PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Aabb |
EPhysics2DDrawFlags.Pair |
EPhysics2DDrawFlags.CenterOfMass |
EPhysics2DDrawFlags.Joint |
EPhysics2DDrawFlags.Shape;
}
start() {
input.on(Input.EventType.TOUCH_START, this.TouchStart.bind(this));
input.on(Input.EventType.TOUCH_MOVE, this.TouchMove.bind(this));
input.on(Input.EventType.TOUCH_END, this.TouchEnd.bind(this));
this.graph.lineWidth = 10.0;
}
TouchStart(touch: EventTouch) {
log("TouchStart")
let sx = this.GetTouchPos(touch.getLocation());
this.graph.moveTo(sx.x, sx.y);
}
TouchMove(touch: EventTouch) {
let sx = this.GetTouchPos(touch.getLocation());
if (this.points.indexOf(sx) != -1) {
return;
}
this.graph.lineTo(sx.x, sx.y);
this.graph.stroke();
this.points.push(v3(sx));
let length = this.points.length;
if (this.points.length > 1) {
let point1 = this.points[length - 2];
let point2 = this.points[length - 1];
// let n = this.graph.node;
let n = new Node();
this.graph.node.addChild(n)
let r2d = n.addComponent(RigidBody2D);
r2d.type = ERigidBody2DType.Kinematic;
let box2d = n.addComponent(BoxCollider2D);
box2d.size.width = v3(point1).subtract(v3(point2)).length();
let direction = v3(point1).subtract(v3(point2));
box2d.size.height = 10;
n.position = v3(point1).add(v3(point2)).divide3f(2, 2, 2);
// box2d.group = 2;
let dir = direction.normalize();
box2d.apply();
let q = quat();
let result = v3(n.right.normalize()).dot(dir);
if (result >= 0) {
n.setWorldRotation(Quat.rotationTo(q, n.right.normalize(), dir));
} else {
n.setWorldRotation(Quat.rotationTo(q, n.right.negative().normalize(), dir));
}
this.r2dList.push(r2d);
}
}
TouchEnd() {
// let r2d = this.graph.node.getComponent(RigidBody2D);
// r2d.type = ERigidBody2DType.Dynamic;
// for(let i =0;i<this.r2dList.length;i++){
// this.r2dList[i].type = ERigidBody2DType.Dynamic;
// }
}
private GetTouchPos(startPos: Vec2) {
let wp = this.camera.screenToWorld(v3(startPos.x, startPos.y));
return this.camera.convertToUINode(wp, this.graph.node);
}
}
貌似不能像unity一样,子物体上只加 BoxCollider2D,不加RigidBody2D 在父物体上加RigidBody2D,然后运行的时候是一个整体,这个需要怎么改,来点大佬帮忙看看,谢了。


