Simple mouse control for gun
Posted: Sun Jan 31, 2010 11:28 am
Frequently new players asks about mouse control things.
Here it is simple and effective example:
How to build:
You need one global variable - scene.my.mspd (motor speed) - type scene.my.mspd = 0 in console.
Now put and fix box on gun at hinge center and hit it with laser (or collide in phun).
All script is in onHitByLaser (onCollide in phun) event of that box.
Set hinge motor "on" and set motorSpeed = {scene.my.mspd}.
Now is most interesting part - script. To determine direction of rotation we need position of gun (e.pos), mouse position (app.mousepos) and current normal vector (e.normal). Idea is to find is mouse on the left side from gun or on the right. It's pretty simple - you need to multiply normal vector on normalized vector from gun to mouse - result is projection (positive or negative) indicating which side to turn.
R = app.mousepos - e.pos (vector from gun to mouse)
Rn = R / |R| (normalized vector with length = 1, |R| - length of R vector)
P = e.normal x R (projection of R on e.normal)
So if P is positive - turn right, negative - left. P can be in -1..+1 interval so it indicates speed of turn too.
Finally, formula:
where - 7 is speed of rotation multiplier (tune it to rotate faster without jitter).
So put formula in onHitBylaser (onCollide in phun) and that's it. Mobile, fast, mouse-controlled gun.
Here it is simple and effective example:
How to build:
You need one global variable - scene.my.mspd (motor speed) - type scene.my.mspd = 0 in console.
Now put and fix box on gun at hinge center and hit it with laser (or collide in phun).
All script is in onHitByLaser (onCollide in phun) event of that box.
Set hinge motor "on" and set motorSpeed = {scene.my.mspd}.
Now is most interesting part - script. To determine direction of rotation we need position of gun (e.pos), mouse position (app.mousepos) and current normal vector (e.normal). Idea is to find is mouse on the left side from gun or on the right. It's pretty simple - you need to multiply normal vector on normalized vector from gun to mouse - result is projection (positive or negative) indicating which side to turn.
R = app.mousepos - e.pos (vector from gun to mouse)
Rn = R / |R| (normalized vector with length = 1, |R| - length of R vector)
P = e.normal x R (projection of R on e.normal)
So if P is positive - turn right, negative - left. P can be in -1..+1 interval so it indicates speed of turn too.
Finally, formula:
- Code: Select all
scene.my.mspd = - 7 * (e.normal(0) * (app.mousepos(0) - e.pos(0)) + e.normal(1) * (app.mousepos(1) - e.pos(1))) / (((app.mousepos(0) - e.pos(0)) ^ 2 + (app.mousepos(1) - e.pos(1)) ^ 2) ^ 0.5)
where - 7 is speed of rotation multiplier (tune it to rotate faster without jitter).
So put formula in onHitBylaser (onCollide in phun) and that's it. Mobile, fast, mouse-controlled gun.