Cocos Creator绕远做圆周运动,且变换运动物体的角度

需求:绕远做圆周运动 并且精灵的角度要随着位置的改变而改变

网上有很多做圆周运动的代码,但是要不然就是角度不变 要不然就是cocos版本老旧

摘了一段3.x的圆周运动,自己加了角度变换

圆周运动,已知,圆点坐标为(0,0)固定不变和圆周上任意一点的坐标。只需要求 圆周上这个点 所在的切线 与x周的角度就行。

Math.atan2(y:number,x:number) 这个函数刚好符合需求

export class xxController extends Component {



  // 汽车
  @property(Sprite)
  sprCar: Sprite = null;

  // 圆心
  @property
  circleCenter: Vec2 = v2(0, 0);

  // 半径
  @property
  circleRadius: number = 250;

  // 车速
  @property
  carSpeed: number = 200;

  // 弧度
  radian: number = 0;

  onLoad() {
    this.schedule(this.circleMove, 0.01);
  }

  circleMove(dt) {
    // 先计算弧度
    this.radian += dt * (this.carSpeed / 100);
    let x = this.circleRadius * Math.cos(this.radian) + this.circleCenter.x;
    let y = this.circleRadius * Math.sin(this.radian) + this.circleCenter.y;
    this.sprCar.node.position = v3(x, y, 0);
    // Math.atan2 反正切函数 返回从X轴到某个点的角度(以弧度为单位)。
    let angle = Math.atan2(y, x) / (Math.PI / 180);
    this.sprCar.node.angle = angle;

    console.log('x = ' + x + '  y = ' + y + '  angle = ' + angle);

  }


}