banner



How To Make Camera Follow Character In Game Maker Dnd

Introduction

Cameras give a mechanism for cartoon dissimilar parts of your room to dissimilar places on the screen, or for drawing merely a single part of your room to encompass the whole screen. For example, in nearly platform games, the camera follows the main character, since if you could see the whole level on the screen then your graphic symbol would be likewise small to run into and there would exist no surprises for the role player. Cameras can also be used in multi-player co-op games, as they permit you to create a split-screen setup in which in 1 part of the screen yous come across one histrion and in another part you run across the other actor. A further instance is in games in which function of the room should scroll (eastward.g. with the primary character) while another role is fixed (for instance some status panel). This tin can all be easily achieved in GameMaker Studio 2 using cameras and view ports, and in this tutorial nosotros'll take you through all the basics of setting up and manipulating custom cameras in your ain projects.

When you create your game, what the player "sees" at any given moment is governed by three different - but connected - things:

  • The Camera: This is essentially a "container" that will be used to hold the unlike view values and set how the room is displayed on screen.
  • The View: This is what the camera sees, based on the position, project and rotation of the photographic camera.
  • The View Port: The expanse of the physical screen where the camera view will be displayed.

The most obvious analogy to understand what is going on is to apply that of an bodily video camera. You lot take a scene that you want to film (the GameMaker Studio iiroom where your game happens), you take a camera to film it with (the GameMaker Studio 2camera evidently), you have a lens that captures what you see (the GameMaker Studio iiview) and you accept a screen that displays what y'all see (the GameMaker Studio 2view port).

undefined

So, when you lot run a game in GameMaker Studio ii, you will have at least one camera, and it will draw what information technology sees (the view) to a view port, which is then shown in the game window to the player. Annotation that this is truthful even if you don't accept views activated in the room settings. If you do non create your ain photographic camera view and view port, GameMaker Studio two will still create a "default" camera and view/viewport based on the dimensions of the start room of the game. Then if your first room is, for example, 800x400, then GameMaker Studio 2 will create a view port that is 800x400 and a camera with a view that covers the whole room. If you then change rooms to one that is a different size - 1024x768, for example - then the game window and view port volition still be 800x400 but the camera view will be 1024x768 (to see the whole room) and then scaled/stretched to fit the smaller view port. This means that if y'all do not actively use cameras and views, you should brand all your game rooms the same size

Annotation: There are ways you tin change the view port and window size using GML so you are not forced to follow the rule higher up, only it's of import to realise how the GameMaker Studio 2 photographic camera and view port system works by default in this respect.

Now that we accept an idea of what it means when nosotros talk most cameras, views and view ports, it'due south time to actually use them. In the demo projection that comes with this tutorial we have a very basic platform game that, when you run it, volition create a game window that occupies the whole screen and shows the entire game room. If you haven't tested information technology still, press Play in the GameMaker Studio 2 IDE and run across it for yourself before continuing (y'all can move the player object using the Pointer Keys and make it jump using the Spacebar.

undefined

The Room Editor

When you have run the default Demo project for this tutorial, you can see what happens when we leave it up to GameMaker Studio ii to fix the default camera... The whole room is shown, but it's been scaled to fit the view port, which in turn may have been scaled to fit the screen. This is far from satisfactory, and and then we are going to fix a camera view in the Room Editor and limit what the actor sees to but what is visible to the photographic camera.

Open the Room Editor now on the resource rGrass (simply double click  on the resources, or utilise the right click menu  and select "open"). With the room editor open, you demand to get to the Room Backdrop window, shown below, and expand the Viewports and Cameras section:

Room Properties Expanded

The commencement thing we are going to do is tick the Enable Viewports and the Articulate Viewport Background options. The starting time option simply tells GameMaker Studio ii that you are going to have over drawing the photographic camera view and setting up the view port, while the second choice clears the application surface with the window colour before drawing the camera view to the view ports (if y'all know that what y'all are drawing will cover the awarding surface then you lot can switch this off, but if in doubt make sure information technology is enabled).

We now need to define our camera view and the area of the screen on which to draw it (the view port).

Note: If you practice not enable whatever cameras or view ports, then the game volition yet run but you will only get a blank window.

For this demo, we only want to take i view agile and have it follow the player, then you want to open Viewport 0 and click the Visible choice:

Make View Visible

You can actually run the demo projection now if you want and you'll already meet a difference. The game window should exist 1024x768 and the camera view focused on the top left corner of the room (these are the default values for the camera view). However, you tin can motion the player outside of the view and the size isn't really what nosotros want...

The kickoff thing we are going to prepare is the size of the game window and expanse within the room, so ready the Camera Properties to take a Width and Tiptop of 960px and 540px respectively, and the Ten pos and Y pos should both be set up to 0 (this sets the size of the camera view and the position inside the room when the room is entered). It's worth noting that these settings are also reflected by the View Overlay in the actual editor window for the room, and the overlay can be toggled on or off using the control button (shown below):

Room View Overlay

We also need to adapt the View Port size to conform the new photographic camera view size, otherwise nosotros volition get stretching like this (run the project and meet for yourself):

View Camera Stretched To Port Size

To prevent this, we need to set the Viewport Properties to be the same every bit the Camera Backdrop, ie: X pos and Y pos set to 0, and a width and pinnacle of 960px and 540px. You can test again and you should see that the game looks as it should, but you might want to take a moment to play with different values for the view port and run into what happens. For example, if you prepare the X pos or Y pos values, then yous'll go a black area where the view port has been showtime and is cartoon "outside" the game window, or if you set the width and meridian to be 480px and 270px and then you'll get the game scaled to half the size.

NOTE: Setting the view port width or height in the first room of the game volition touch on the size of the game window, only changing the view port offset values will not bear upon the window position.


Camera Following

We take a camera view and a view port prepare up in the room editor, only information technology still doesn't follow the histrion when they motion. Setting up view following is also achieved from the Viewports department of the Room Properties, underneath where we set the photographic camera and port properties:

Object Following Room Properties

The first affair to practise is select an object to follow. This is done by clicking  on the button which currently says "No Object". This will open upwardly the Nugget Explorer where you can select one of the bachelor game Objects, in this case the object "oPlayer". This is telling GameMaker Studio 2 that the view should follow an example of this object if information technology is found in the room.

Notation: If in that location is no instance of the object in the room then the view will just not move, and if at that place is more than one instance of the object in the room GameMaker Studio 2 will cull i to follow, but y'all accept no style of telling which one it will choose.

You tin run the project again at present and move the thespian around. You'll see that when the actor gets close to the edge of the screen the view will movement... but this isn't really very good every bit the player cannot see what is coming and we want the view to move and keep the player in the center. For that, we need to alter the horizontal and vertical collision border that the camera view uses to "focus" on the object:

Object Following Border

This border is the altitude from the edges of the screen that the instance needs to be before the camera will update its position to follow the example. In this case, it'southward set to 32px, which means that the view volition merely motility if the instance is 32px or less from the edge. Nosotros need to alter these values to 400px for the horizontal edge and 250px for the vertical edge. These values leave a picayune bit of "space" for the player to move in before the view starts to move, merely requite a big enough view around the player to be helpful.

Note: If you set the border values to anything over half the width and height of the room, the follow case will be clamped to the center of the view.

The Object Post-obit preferences besides permit yous to prepare a speed for horizontal and vertical scrolling. The values set here tell GameMaker Studio two how many pixels to update the view position per-stride for the horizontal and vertical axis, and so y'all can have views that "slide" into position. For example, if you set the horizontal speed to ii and exam the project, you can see that when the player moves left or right the camera view will lag behind and but "take hold of upward" when the player stops moving. However, this is not what nosotros want, and so nosotros ready it to -1, which is how nosotros tell GameMaker Studio 2 to update the position instantly.

Annotation: Setting the horizontal or vertical speed to 0 will prevent the camera from post-obit the case on that axis, and also annotation that regardless of the edge or speed values, the view will never get outside of the room when using the Room Editor view preferences (this is possible in code, though).

Play the game again and y'all can run across that the player tin can move left or right, upwards or down and the view will follow them effectually. At present, let's expect at how to set this up using code...

Creating Cameras

We are now going to motion on and make a camera using the GameMaker Language (GML). To get-go with, nosotros are going to prepare the aforementioned camera and view port as we accept in the room editor, merely using code, and then open the Room Editor merely now and un-check the Enable Viewports option in the Room Properties:

Switch Off Views In The Room Properties

With that washed, running the game will once more create a window the width of your display and show the full room scaled down to fit, so nosotros at present need to add some code to fix this. You lot need to open the controller object "oGame" for this (a controller object is an object, generally with no sprite assigned, that is placed in a room to "control" things behind the scenes, and is generally used for room setup and drawing HUDs to the GUI, etc...). With "oGame" open, click the Create Issue to open it:

Game Controller Object Create Event

Here we are going to set up all the view port properties likewise as create a camera and define what it views. To get-go with, we need to enable custom viewports and cameras, equally well as enable a specific view port to use. For that we add together the following afterward the existing code:

oGame: Create Event
            // Initialise Viewports
view_enabled = truthful;
view_visible[0] = true;


The first line is just an identifying comment so we don't get lost in the code, while the 2d line sets the congenital-in global scope variable view_enabled to true. This variable tin can be set to true or simulated and mimics the Enable Viewports checkbox in the Room Properties of the room editor.

The second line tells GameMaker Studio 2 which viewport to enable. If you await in the Room Editor, you can see that you accept available up to 8 view ports, and and so to access them in code we utilize an array, where the first view is the [0] element, and the last view is the [7] element. A number of the born values for view ports are stored as global scope arrays, so make certain that the array element you are accessing corresponds to the view you desire to use or change.

With that done, nosotros can now setup the viewport itself using the following code:

oGame: Create Issue
            view_xport[0] = 0;
view_yport[0] = 0;
view_wport[0] = 960;
view_hport[0] = 540;


Here we target the view port [0] array, since that is the port that we fabricated visible previously, and we set the offset position to (0,0), and the width and superlative to 960px and 540px, respectively. This is exactly the same every bit what we had in the room editor for the Viewport Properties.

Annotation: These view port array values can be read as well every bit written to, so you can set up views in the Room Editor, for example, and then get the values set in GML using these built-in arrays.

We tin now go ahead and gear up our camera view. This is easily done with a single function which not only sets the view position and size, but will likewise fix the object that the photographic camera has to follow and the follow borders:

oGame: Create Upshot
            view_camera[0] = camera_create_view(0, 0, view_wport[0], view_hport[0], 0, oPlayer, -one, -i, 400, 250);


The function camera_create_view() creates a new camera and sets upward the view from that camera, and you supply the same values that you'd supply to the room editor for the Photographic camera Backdrop and the Follow Object. The office then returns a unique ID value for the camera that has been created. At present, you can simply shop this ID value in a regular variable and so apply it whenever yous desire, since cameras are really dynamic resources that can exist created and destroyed and passed effectually much like whatever other resource. This means that the act of creating a camera does non actually draw anything to the screen, and is instead "preparing" a photographic camera for utilize, and so you could potentially have diverse cameras setup and so assign them one at a fourth dimension to a view port to create a cut-scene, for example. However, in this case we return the ID of the photographic camera to the built-in global array view_camera. This array is what connects a camera to a view port, so past giving the [0] element our camera ID nosotros are telling GameMaker Studio 2 to draw everything that camera "sees" to the screen.

Let'due south run the game at present and see how information technology works...

Stretched Game Window

Something isn't quite correct at that place, is it? You lot may be thinking that you've done something wrong at this signal, but don't worry, you haven't! What you lot are seeing is a issue of the lawmaking only setting the camera and view ports, but not setting the things that GameMaker Studio ii does automatically for you lot when you use the Room Editor to set upwardly cameras. Previously we mentioned that when you accept no view active in the Room Editor, GameMaker Studio two will set the game window to the size of the beginning room of the game, then now that we no longer set the view in the Room Editor, GameMaker Studio two is setting upwards the "default" camera and view ports before our code takes over. This sets the game window to exist the wrong size.

The solution to the problem outlined above is to set the window to the correct size for the view port that we have set using the following office:

oGame: Create Effect
            var _dwidth = display_get_width();
var _dheight = display_get_height();
var _xpos = (_dwidth / 2) - 480;
var _ypos = (_dheight / 2) - 270;
window_set_rectangle(_xpos, _ypos, 960, 540);


This sets the window to the same size every bit the view port nosotros accept defined. Note that nosotros have used the function window_set_rectangle() rather than simply using window_set_size() because resizing the window will not reposition it, meaning that it will be resized at the position of the original top left corner. This style nosotros resize it and position information technology correctly in the center of the display.

Run the game again and see what happens...

The Application Surface Is The Wrong Size

The window is now the correct size but... it's is nonetheless not right. What have we done incorrect? Again, this is an result with the automated things that GameMaker Studio 2 does when initialising a room. Non just does it set the window size based on the view port, it also sets the size of the Application Surface. This surface is what everything y'all draw in the Depict Event is sent to before beingness displayed on the screen, so by default it will exist created at the size of the room if no view port is defined in the Room Editor (and it will be created the size of the view port if one is defined). We need to resize this merely the aforementioned every bit we did the game window with the following code:

oGame: Create Event
            surface_resize(application_surface, 960, 540);


If you run the game at present, information technology should all look exactly equally it did before when you used the Room Editor to set up the views:

Camera Correctly Set Up

Earlier we proceed, there is 1 last - simply very important - stride to take, and that is to destroy the camera at the cease of the room. As mentioned previously, cameras are considered a dynamic resources, much like particles, or surfaces or information structures, and as such they are allocated a retentiveness space when they are created. If you do not destroy the photographic camera when it is non required you run the risk of creating a "retentiveness leak", which is what happens when you commencement to make full up memory infinite with references to dynamic resource that tin can no longer be accessed by GameMaker Studio 2. To set up this issue we need to add a Clean Upward result to our controller object "oGame". Add this consequence now and give it the following code:

oGame: Clean Up Event
            /// Clean Up Cameras
camera_destroy(view_camera[0]);


All this does is frees up the memory for the camera assigned to the view port element [0]. This is an of import pace to remember, so keep information technology in mind when creating cameras in your own projects!

Advanced Moving

What we have at the moment is a basic replica of what we set originally in the room editor, which is fine for uncomplicated games and basic motion, simply what if nosotros want something more than complex? Well, at that place are a number of functions bachelor for dealing with cameras and we can make use of some of them to make the view a bit more than dynamic. In this case, we're going to make the view change position depending on what keys are pressed, so that the role player can encounter a little more of the room in the direction of movement.

To start with, nosotros need to deactivate object following in the camera, equally we will practise this manually through code after. For that, you simply need to open the Create Event of the object "oGame" and modify the line where we create the photographic camera to this:

oGame: Create Outcome
            view_camera[0] = camera_create_view(0, 0, view_wport[0], view_hport[0], 0, noone, -1, -1, -i, -one);


Past setting the follow object to the keyword noone, we are telling GameMaker Studio 2 that this camera should not automatically follow anything. Now open the object "oPlayer" and go to the Step Upshot. Beneath the phone call to the script scrProcessPlayer we are going to add in the following code:

oPlayer: Step Event
            var _hor = keyboard_check(vk_right) - keyboard_check(vk_left);
var _ver = keyboard_check(vk_down) - keyboard_check(vk_up);


This code gets a value that is either -ane, 0, or 1 for both horizontal and vertical motility past checking the appropriate keys (on the horizontal axis it volition render -one for left and 1 for right, and on the vertical centrality information technology will return -one for upward and 1 for down). We volition use these values subsequently to fix the distance from the actor that the view should move to show more in that management.

We adjacent need to become the current position and size of the camera view so that nosotros can change it:

oPlayer: Pace Effect
            var _viewX = camera_get_view_x(view_camera[0]);
var _viewY = camera_get_view_y(view_camera[0]);
var _viewW = camera_get_view_width(view_camera[0]);
var _viewH = camera_get_view_height(view_camera[0]);


So, start we go the current position of the camera view assigned to view port element [0], and then nosotros go the width and acme. We demand this because nosotros will subtract half of those values from the current player position to correctly eye the window, which nosotros'll do with the following:

oPlayer: Step Event
            var _gotoX = x + (_hor * 200) - (_viewW * 0.5);
var _gotoY = y + (_ver * 150) - (_viewH * 0.5);


Then, we at present have local variables holding the electric current view position and the position we want the view to actually motion to. At present, we could but set the camera to the new position and leav e it at that, only the movement will be actually sharp and not very pleasant for the actor. To get effectually this nosotros are going to use the lerp function to ease the photographic camera into position (using linear interpolation between the current and goto positions):

oPlayer: Step Outcome
            var _newX = lerp(_viewX, _gotoX, 0.1);
var _newY = lerp(_viewY, _gotoY, 0.1);


Now nosotros tin apply these x/y values to set the camera:

oPlayer: Step Event
            camera_set_view_pos(view_camera[0], _newX, _newY);


Notation that throughout the code we refer to the view_camera assortment, since this holds the ID of the photographic camera that we want to edit, only you lot can employ these functions to edit any camera view at whatsoever fourth dimension, regardless of whether it is an agile camera (ie: assigned to a view port) or not. You would simply substitute the view_camera array for the variable that holds the camera ID to be modified.

Your Step Event for the object "oPlayer" should now expect like this:

oPlayer Step Event Code

If all has gone correctly, when yous run the game you should at present have something that looks like this:

Camera Easing Example


Adding Zoom

The camera view now yet follows the player around the room, but it does so in a more "organic" fashion, easing into different positions depending on the direction keys that the user has pressed. This is a great way to let the player run across a scrap more of the room and then avoid traps or enemies etc... Even so, the electric current setup has a problem, which is that the photographic camera tin leave the room bounds. This is fine for some games, but for this one information technology'south not very adept, as you can see the "edge" of the room which breaks immersion. This needs to be dealt with but nosotros'll do it as we add the next feature... zoom.

Another fashion we tin can employ camera views is to zoom the visible expanse of the room in and out. For this we'll use the mouse bicycle  to command the "level" of zoom. To first with, we need to accept the "oPlayer" Create Upshot open, as we are going to add a new example scope variable to control the zoom factor:

oPlayer: Create Upshot
            zoomF = one;


This will be the multiplying factor that we'll use to ready the size of the photographic camera view and then zoom in and out, where 1 is a zoom factor ane:1 with the view port, and less than one will be zooming in and greater than 1 volition zoom out. With that added, we demand to go to the "oPlayer" Stride Event and add this afterwards the code we already have:

oPlayer: Pace Upshot
            var _factor = 0.2;
var _mouseW = mouse_wheel_down() - mouse_wheel_up();
zoomF = clench(zoomF + (_mouseW * _factor), _factor, 2);


Here nosotros gear up a variable to the value that we desire to add together/subtract to the zoom cistron, and then we check the mouse wheel for motility (as we did with the keyboard checks before, where i is wheel down, 0 is no movement, and -i is mouse wheel up). The final line is where we gear up the zoomF instance variable to the new value for zooming. Notice that here we use the office clamp to make sure that the returned value does not go beneath 0.two or above 2. Nosotros obviously don't want the user to zoom out too far or in too much, and then using clamp permits us to control this, and we'll exist using information technology again several times in the following code.

The next block of lawmaking to add after that is the following:

oPlayer: Step Event
            var _lerpH = lerp(_viewH, zoomF * 540, _factor);
var _newH = clamp(_lerpH, 0, room_height);
var _newW = _newH * (960 / 540);
camera_set_view_size(view_camera[0], _newW, _newH);


The code above uses linear interpolation on the current camera view meridian, using our new zoom value and the amount to add together/decrease, to create a new value for the elevation. Why are we using the height for this? Well, the room is longer than it is higher, and then we don't want the zoom to be whatsoever larger than the height otherwise we'll be showing the "outside" are, so our maximum zoom level is the one that takes us to that value and no college. We ensure this on the next line where we use clamp over again to make sure that our lerped value is no larger than the room tiptop.

Nosotros need to scale the camera view width too, which we do past taking the new height and multiplying it by the aspect ratio of the "base of operations" zoom, earlier finally using these values to set the size of the photographic camera view.

Now, we could just leave it at that, and if y'all run the project now and then you lot'll encounter it works. Sort of! The zoom works fine but will non zoom in to the surface area around the player, but rather to the electric current photographic camera position, which then lerps to bear witness the player due to the code nosotros have for following. This is far from ideal and then we need to remove this line of code that nosotros have already:

oPlayer: Step Effect
            camera_set_view_pos(view_camera[0], _newX, _newY); // Remove this line


The following code should now exist added after all the other code in the outcome:

oPlayer: Footstep Event
            var _offsetX = _newX - (_newW - _viewW) * 0.5;
var _offsetY = _newY - (_newH - _viewH) * 0.5;
_newX = clench(_offsetX, 0, room_width - _newW);
_newY = clench(_offsetY, 0, room_height - _newH);
camera_set_view_pos(view_camera[0], _newX, _newY);


First we get the offset values for the view based on the previously calculated view position minus the departure between the old view width/elevation and the new view width/height. We so clamp these values to ensure that they are within the confines of the room surface area so we don't come across anything outside, and and so finally we set the camera position.

Your full code cake for the Pace Event of the object "oPlayer" should now look similar this:

oPlayer Step Event Code

If all has gone correctly, when you run the game you should now have something that looks like this:

Camera Zooming Example

Summary

That brings united states to the end of our Cameras And Views tutorial. By finishing this tutorial you lot should now have the following bones knowledge:

  • What the difference is between a camera, the view, and the view port.
  • How to set upwardly a camera view and a view port in the room editor.
  • How to make a photographic camera follow an instance of an object.
  • How to prepare up a camera - and accept it follow an object instance - using code.
  • How to get values from a photographic camera and then use them to change its position.
  • How to create a zoom effect.

You lot should take some time now to play with the demo and see what else you can do with cameras. For example, you could add together a screen milkshake upshot when the player hits a ghost using the camera view angle value - the code would look something like this:

oPlayer: Create Result
            shakeMag = 0;          
oPlayer: Collision With Ghost Event
            shakeMag = 20;          
oPlayer: Stride Outcome
            if shakeMag > 0.1 { shakeMag -= shakeMag / five;
}
else shakeMag = 0; camera_set_view_angle(view_camera[0], -shakeMag + random(shakeMag * 2));

Or maybe add a 2d view to evidence a "mini map" of the whole room? The lawmaking for that would look something like this:

oGame: Create Upshot
            view_visible[1] = true; view_xport[1] = 32; view_yport[one] = view_hport[0] - (room_height / 10) - 32; view_wport[1] = room_width / 10; view_hport[1] = room_height / 10; view_camera[1] = camera_create_view(32, 32, room_width, room_height, 0, noone, -1, -1, 0, 0);          

Or if you feel like tackling something more complicated, how about making the game have ii players and so split the game window between them? That'southward a scrap more than we can fit into this summary, merely at that place is a Demo projection chosen Dissever Screen Cameras which shows how this can be done. Any you do, we hope yous have a better grasp of cameras now and can use them in your projects to maximum consequence.

Source: https://gamemaker.io/en/tutorials/cameras-and-views

Posted by: bennettandonellove.blogspot.com

0 Response to "How To Make Camera Follow Character In Game Maker Dnd"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel