Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How would I set Camera recoil and then return back to its last position?

Asked by 7 years ago

So lets say I was shooting my gun and the max recoil of the camera would be moving 3 up so kind of like Camera.CFrame=Camera.CFrame*CFrame.Angles(math.rad(1),0,0)) and everytime you tapped fire it would move 1 up and then the camera would stop going up after it moves up 3. -- How would I detect this?

Then how would I return the Camera's position back to the last position before the person shot his gun?

I tried using for loops, counters that stopped camera movement after it moved up 3, and others, but they all failed at the end. Thank you for answering if you did, really appreciate it!

1 answer

Log in to vote
0
Answered by
EgoMoose 802 Moderation Voter
7 years ago

The common way this is dealt with is through springs. This allow the game coder to set some values regarding how the spring moves and then update the target. This allows you to change the spring target dynamically and not have to worry about the for loop timing or other animations.

There's a wiki article on this topic, that gives a broad overview of the concept that can be read here, but to really understand how I got to the code I'm about to post you'll need to do some calculus.

01-- module
02local spring = {};
03local spring_mt = {__index = spring};
04 
05function spring.new(position, velocity, zeta, omega)
06    local self = {};
07    self.position = position;
08    self.velocity = velocity;
09    self.zeta = zeta;
10    self.omega = omega;
11    self.target = position;
12    return setmetatable(self, spring_mt);
13end;
14 
15function spring:update(dt)
View all 36 lines...

With that we can easily set targets and update them properly with a time step.

Here's a very simple example wherein I use the spring to bring the angle back down, but potentially you also want to use it to go up too.

01local mouse = game.Players.LocalPlayer:GetMouse();
02local camera = game.Workspace.CurrentCamera;
03local part = game.Workspace.Part;
04local spring = require(game.Workspace.Spring);
05 
06local s = spring.new(0, 0, 0.6, 10);
07mouse.Button1Down:connect(function()
08    s.position = 10; -- up angle
09end);
10 
11game:GetService("RunService").RenderStepped:connect(function(dt)
12    s:update(dt);
13    part.CFrame = camera.CFrame * CFrame.Angles(math.rad(s.position), 0, 0) * CFrame.new(1, -1, -3);
14end)

Hopefully you get the jist!

0
Man, gotta wait 2 years to get in Calculus but your answer seems right so I'll accept it. Thank you. Mr_MilkysButler 47 — 7y
Ad

Answer this question