ball_v2_0.wrl source
#VRML V2.0 utf8

Viewpoint {}
NavigationInfo {
type "EXAMINE"
}

# 赤球
DEF Ball-Tf Transform {
children [
Shape {
appearance Appearance {
material Material {
diffuseColor 1 0 0
}
}
geometry Sphere {
radius 0.2
}
}
]
}

# 青箱
Transform {
children [
Shape {
appearance Appearance {
material Material {
diffuseColor 0 0 1
transparency 0.6
}
}
geometry Box {
size 5 5 0.05
}
}
]
}


# タイムセンサー
DEF TiS TimeSensor {
cycleInterval 0.05
loop TRUE
}

# スクリプト
DEF Sc Script {
eventIn SFTime set_cycleTime
eventOut SFVec3f posBall
field SFVec3f moveVec 0 0 0
url "javascript:

function initialize () {

// 赤球の進行方向をセットする。
moveVec.x = Math.random() * 2 - 1;
moveVec.y = Math.random() * 2 - 1;
moveVec.z = 0;

// 赤球のスピードを 0.05 にセットする。
moveVec = moveVec.normalize().multiply( 0.05 );

// 赤球の位置をセットする。
posBall.x = Math.random() * 2 - 1;
posBall.y = Math.random() * 2 - 1;
posBall.z = 0;

}

function set_cycleTime () {

// 赤球の新しい位置をセットする。
posBall = moveVec.add( posBall );

// もし赤球が青箱の外に出るならば、進行方向を変えて箱の内側に移す。
if ( posBall.x > 2.3 || posBall.x < -2.3 ) {

moveVec.x = -moveVec.x;
posBall.x = Math.max( -2.3, Math.min( 2.3 , posBall.x ));

}

if ( posBall.y > 2.3 || posBall.y < -2.3 ) {

moveVec.y = -moveVec.y;
posBall.y = Math.max( -2.3, Math.min( 2.3 , posBall.y ));

}
}

"
}

ROUTE TiS.cycleTime TO Sc.set_cycleTime
ROUTE Sc.posBall TO Ball-Tf.translation