利用自由落体公式根据起始高度算出落地时间,然后利用关键帧动画结合插值计算模拟出小球自由落体的动效,关键步骤如下:
displayInfo = display.getDefaultDisplaySync(); // 活动区域 maxHeight = this.getUIContext().px2vp(this.displayInfo.height) * 0.85; // 坐标x maxWidth = this.getUIContext().px2vp(this.displayInfo.width); middleX = this.maxWidth * 0.03; // 起始坐标y @State sportY: number = 0;
generatePosition(): Array<KeyframeState> { // 根据自由落体公式求得时间 let time = Math.sqrt(2 * this.maxHeight / 9.8); let result: Array<KeyframeState> = []; // 第一次落地的速度为v=gt,反弹假设损失0.1的动能,速度为原来的0.9,则第二次的高度为原来的90%,时间0.9*time for (let i = 0; i < 17; i++) { let flag = i % 2 == 0; result.push({ // 一帧等于17ms,1s约等于17ms*63 duration: time * 63 * Math.pow(0.9, Math.ceil(i / 2)), curve: flag ? Curve.FastOutLinearIn : Curve.LinearOutSlowIn, event: () => { this.sportY = flag ? this.maxHeight : this.maxHeight - 9.8 / 2 * Math.pow(time * Math.pow(0.9, Math.ceil(i / 2)), 2); } }); } return result; }
import { display } from '@kit.ArkUI'; @Entry @Component struct FreeFallDemo { uiContext: UIContext = this.getUIContext?.(); displayInfo = display.getDefaultDisplaySync(); // 活动区域 maxHeight = this.getUIContext().px2vp(this.displayInfo.height) * 0.85; // 坐标x maxWidth = this.getUIContext().px2vp(this.displayInfo.width); middleX = this.maxWidth * 0.03; // 起始坐标y @State sportY: number = 0; generatePosition(): Array<KeyframeState> { // 根据自由落体公式求得时间 let time = Math.sqrt(2 * this.maxHeight / 9.8); let result: Array<KeyframeState> = []; // 第一次落地的速度为v=gt,反弹假设损失0.1的动能,速度为原来的0.9,则第二次的高度为原来的90%,时间0.9*time for (let i = 0; i < 17; i++) { let flag = i % 2 == 0; result.push({ // 一帧等于17ms,1s约等于17ms*63 duration: time * 63 * Math.pow(0.9, Math.ceil(i / 2)), curve: flag ? Curve.FastOutLinearIn : Curve.LinearOutSlowIn, event: () => { this.sportY = flag ? this.maxHeight : this.maxHeight - 9.8 / 2 * Math.pow(time * Math.pow(0.9, Math.ceil(i / 2)), 2); } }); } return result; } build() { Column() { Button('点击') .width('80%') .onClick(() => { if (!this.uiContext) { return; } let rs = this.generatePosition(); // 只循环1次,每次的坐标变换由position决定 this.uiContext.keyframeAnimateTo({ iterations: 1 }, rs); }); Stack() { Circle().width(50).height(50).position({ x: this.middleX, y: this.sportY }); }; }.width('100%').height('100%'); } }