Hello, I started this thread in hopes of strengthening my organization skills with programming.
I had a similar previous thread for something like this, and now with little more experience and practice I’ll be posting more of my code for you guys to critique!
Instead of just one piece of code I’ll be posting snippets here and there for feedback.
I’ll always provide context for code in question.
Let’s get started,
I wrote this small function for a camera script I’m working on. I want to limit the zoom distance in and out, the camera’s distance to the player can’t be over “max” and it can’t be less than “min”. The “pivot” is the player and the “cam_pos” is the camera position object (it’s just an empty with the camera as its child). “vel” is the velocity in which the camera is zooming in or out.
def zoom_limit(self, vel, min, max, pivot, cam_pos): next = vel + cam_pos.worldPosition dist_vec = pivot.worldPosition - next if dist_vec.magnitude < min: min_vec = dist_vec.copy() min_vec.magnitude = min extra = -dist_vec + min_vec vel += -extra elif dist_vec.magnitude > max: max_vec = dist_vec.copy() max_vec.magnitude = max extra = dist_vec - max_vec vel += extra return vel
The function basically checks if the next position will be too close to the player (less than min) or too far from the player (more than max), with that information it adjusts the velocity so the cam_pos doesn’t go further than it’s supposed to and I return the altered velocity.
The function is used like this:
velocity = self.zoom_limit(velocity, self.min_zoom, self.max_zoom, self.pivot, self.cam_pos)
Problems that I already see but don’t know how to fix (these I want to address first):
- The code is repeating itself in two if statements. Is there anyway to make it a general if?
- I think I have too many parameters, anyway to shorten this? (Inside or outside the code)
Here is the full zoom state code for the camera:
def zoom(self): self.face_player() cam_vec = self.input.cam_vec y_vel = cam_vec.y*self.fix_sens velocity = self.cam_pos.worldOrientation*mt.Vector((0, y_vel, 0)) if velocity.magnitude: velocity = self.zoom_limit(velocity, self.min_zoom, self.max_zoom, self.pivot, self.cam_pos) self.cam_pos.worldPosition += velocity if self.input.key_up("zoom"): self.state = "look"