You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

After Effects:实现屏幕边界反弹及随机初始运动方向

问题描述

想要重现早年电视上DVD标识的运动效果(屏幕内移动、触碰边界反弹),已实现基础效果,但所有应用脚本的对象初始运动方向均为右下,初始阶段表现不符合预期,需修正。

原脚本代码:

// 初始化随机数生成器,确保起始位置和速度的随机值一致
seedRandom(index, true);

// 随机起始位置
startX = random(0, thisComp.width);
startY = random(0, thisComp.height);

// 随机速度
speed = random(50, 150); 

// 计算从开始到当前的移动距离
distanceMovedX = time * speed + startX ;
distanceMovedY = time * speed + startY ;

// 有效宽高为合成的宽高
effectiveWidth = thisComp.width ;
effectiveHeight = thisComp.height ;

// 计算X、Y方向上完成的完整"往返次数"(来回为2次单程)
numTripsX = Math.floor(distanceMovedX / effectiveWidth);
numTripsY = Math.floor(distanceMovedY / effectiveHeight);

// 计算扣除完整往返后,当前单程内的剩余距离
positionInCurrentTripX = distanceMovedX % effectiveWidth;
positionInCurrentTripY = distanceMovedY % effectiveHeight;

// 若往返次数为奇数则反向运动,否则保持初始方向
newX = (numTripsX % 2 === 0) ? positionInCurrentTripX : effectiveWidth - positionInCurrentTripX;
newY = (numTripsY % 2 === 0) ? positionInCurrentTripY : effectiveHeight - positionInCurrentTripY;

[newX, newY];
问题根源

原脚本中X、Y方向使用了相同的正速度值(time * speed),导致初始运动方向固定为右下。要实现随机初始方向,需为X、Y方向分别分配带正负符号的随机速度分量。

修正方案

核心修改点:

  • 将统一的speed拆分为xSpeed和ySpeed,分别随机生成正负方向的速度
  • 调整位移计算逻辑,使用各自方向的速度分量
  • 补充负位移的边界处理,避免初始速度为负时位置异常

修正后的完整代码:

// 初始化随机数生成器,确保每个对象的随机值独立
seedRandom(index, true);

// 随机起始位置
startX = random(0, thisComp.width);
startY = random(0, thisComp.height);

// 为X、Y方向分别生成带随机正负的速度(速度大小50-150)
xSpeed = random(-1, 1) * random(50, 150);
ySpeed = random(-1, 1) * random(50, 150);

// 计算X、Y方向的累计位移(基于各自速度)
totalDisplacementX = time * xSpeed;
totalDisplacementY = time * ySpeed;

// 计算当前的绝对位置(起始位置+累计位移)
absoluteX = startX + totalDisplacementX;
absoluteY = startY + totalDisplacementY;

// 有效宽高为合成的宽高
effectiveWidth = thisComp.width;
effectiveHeight = thisComp.height;

// 计算X方向的往返次数与当前单程位置
numTripsX = Math.floor(absoluteX / effectiveWidth);
positionInCurrentTripX = absoluteX % effectiveWidth;

// 计算Y方向的往返次数与当前单程位置
numTripsY = Math.floor(absoluteY / effectiveHeight);
positionInCurrentTripY = absoluteY % effectiveHeight;

// 根据往返次数奇偶性确定当前方向,计算最终位置
newX = (numTripsX % 2 === 0) ? positionInCurrentTripX : effectiveWidth - positionInCurrentTripX;
newY = (numTripsY % 2 === 0) ? positionInCurrentTripY : effectiveHeight - positionInCurrentTripY;

// 处理负位移的边界情况(当初始速度为负,absoluteX/Y为负数时)
newX = newX < 0 ? effectiveWidth + newX : newX;
newY = newY < 0 ? effectiveHeight + newY : newY;

[newX, newY];
关键细节说明
  1. 随机速度方向:random(-1,1)会生成-1到1之间的随机数,乘以速度大小后,即可得到正负随机的速度分量,实现左上、右上、左下、右下等任意初始方向。
  2. 负位移处理:当初始速度为负(比如向左/向上),absoluteX/Y可能为负数,此时取模运算会得到负的positionInCurrentTripX/Y,通过最后一行的判断将其转换为屏幕内的有效位置。
  3. 保持随机性独立:seedRandom(index, true)确保每个应用脚本的对象都有独立的随机起始位置和速度,避免重复运动轨迹。

内容的提问来源于stack exchange,提问作者Madar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:43:26