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);

  }


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM