物体在一个正方形区域里面做永不停止的随机运动,请问怎么实现呢?
状态机
分分别写
几个模块
interface state{
update(dt)
end(){}
}
class moveState imp state {}
class runState imp state {}
class stateMager {
stateKv:{} = null
currentState = null
update(){}
checkoutState(){}
}
ai 写的
import { Size } from "cc";
import { UITransform } from "cc";
import { _decorator, Component, Vec3 } from "cc";
const { ccclass, property } = _decorator;
@ccclass("RandomMovement")
export class RandomMovement extends Component {
@property(Number)
speed = 100;
private _parentSize: Size = new Size();
private _startPos: Vec3 = new Vec3();
start() {
const parent = this.node.parent!;
this._parentSize.set(parent.getComponent(UITransform)!.contentSize);
this._startPos.set(this.node.getPosition());
}
update(dt: number) {
const direction = new Vec3(Math.random() * 2 - 1, Math.random() * 2 - 1, 0);
const movement = direction.normalize().multiplyScalar(this.speed * dt);
const nextPos = this.node.getPosition().clone().add(movement);
if (nextPos.x < -this._parentSize.x / 2 || nextPos.x > this._parentSize.x / 2) {
nextPos.x = Math.min(Math.max(nextPos.x, -this._parentSize.x / 2), this._parentSize.x / 2);
}
if (nextPos.y < -this._parentSize.y / 2 || nextPos.y > this._parentSize.y / 2) {
nextPos.y = Math.min(Math.max(nextPos.y, -this._parentSize.y / 2), this._parentSize.y / 2);
}
this.node.setPosition(nextPos);
}
}
双色球把外框换成方的,没用物理可以一直不停