Implement a box object that can be picked up and put down
/// @function playerCollision
/// @description Handles the player's collision code
function playerCollision() {
var scale = 64/500; // The scale factor of the player object
code
// Floor
var mySolid = instance_place(x, y + global.yspeed, objSolid);
if (mySolid >= 0 && global.yspeed >= 0) {
var spriteOffsetY = sprite_get_yoffset(sprite_index) * scale;
var spriteHeight = sprite_get_height(sprite_index) * scale;
y = mySolid.bbox_top - (spriteHeight - spriteOffsetY);
ground = true;
global.yspeed = 0;
// Ensure the player stays grounded
while (!place_meeting(x, y + 1, objSolid)) {
y += 1;
}
}
// Wall
mySolid = instance_place(x + global.xspeed, y, objSolid);
if (mySolid >= 0 && global.xspeed != 0) {
var spriteOffsetX = sprite_get_xoffset(sprite_index) * scale;
var spriteWidth = sprite_get_width(sprite_index) * scale;
if (global.xspeed < 0) {
x = mySolid.bbox_right + spriteOffsetX;
} else {
x = mySolid.bbox_left - (spriteWidth - spriteOffsetX);
}
// Force player out of the wall if clipping occurs
while (place_meeting(x, y, objSolid)) {
x += sign(global.xspeed) * -1;
}
global.xspeed = 0;
}
// Ceiling
mySolid = instance_place(x, y + global.yspeed, objSolid);
if (mySolid >= 0 && global.yspeed < 0) {
var spriteOffsetY = sprite_get_yoffset(sprite_index) * scale;
y = mySolid.bbox_bottom + spriteOffsetY;
// Force player out of the ceiling if clipping occurs
while (place_meeting(x, y, mySolid)) {
y += 1;
}
global.yspeed = 0;
}
mySolid = instance_place(x, y + global.yspeed, objTopSolid);
if (mySolid >= 0 && global.yspeed >= 0) {
if (bbox_bottom <= mySolid.bbox_top + global.yspeed) { // Check if actually above the platform
var spriteOffsetY = sprite_get_yoffset(sprite_index) * scale;
var spriteHeight = sprite_get_height(sprite_index) * scale;
y = mySolid.bbox_top - (spriteHeight - spriteOffsetY);
ground = true;
global.yspeed = 0;
}
}
// Ensure ground state and yspeed are consistent
if (ground) {
global.yspeed = 0;
// Double-check ground state
if (!place_meeting(x, y + 1, objSolid) && !place_meeting(x, y + 1, objTopSolid)) {
ground = false;
}
}
Assistant
}
/// @function playerStep
/// @description Handles general step event code for the player
function playerStep() {
code
//Check for ground
if place_meeting(x, y+global.yspeed+1, objSolid) || (place_meeting(x, y+global.yspeed+1, objTopSolid) && global.yspeed >= 0)
{
var endCheck = false;
if place_meeting(x, y+global.yspeed+1, objSolid)
{
ground = true;
endCheck = true;
}
if keyboard_check(vk_down) && place_meeting(x, bbox_bottom+1, objTopSolid)
{
y += 1;
}
if place_meeting(x, y+global.yspeed+1, objTopSolid) && !endCheck
{
var topSolid = instance_place(x, y+global.yspeed+1, objTopSolid);
if (bbox_bottom <= topSolid.bbox_top)
{
ground = true;
}
else
{
ground = false;
}
endCheck = true;
}
if !endCheck
{
ground = false;
}
}
else
{
ground = false;
if prevGround == true
y += 1; //To make Mega Man able to fall through 1-block wide gaps
}
//Can we do a short hop? (Placed earlier in the code to fix the 'jump on the frame you land and you can't do a short hop' bug
if !(ground == false && canGravity == true)
canMinJump = true;
//Movement (includes initializing sidestep while on the ground)
if canMove == true
{
if ground == true
{
if keyboard_check(vk_left) && !keyboard_check(vk_right)
{
if canInitStep == true
{
canInitStep = false;
isStep = true;
image_xscale = 64/500;
}
else if isStep == false
{
if !(place_meeting(x, y+1, objIce) && global.xspeed > 0)
{
//Normal physics
if !place_meeting(x-1, y, objSolid)
global.xspeed = -walkSpeed;
}
else
{
//Ice physics
if !place_meeting(x-1, y, objSolid)
global.xspeed -= iceDecWalk;
}
image_xscale = -abs(image_xscale);
if canSpriteChange == true
{
sprite_index = sprWalk;
image_speed = 0.15;
}
}
}
else if keyboard_check(vk_right) && !keyboard_check(vk_left)
{
if canInitStep == true
{
canInitStep = false;
isStep = true;
image_xscale = 64/500;
}
else if isStep == false
{
if !(place_meeting(x, y+1, objIce) && global.xspeed < 0)
{
//Normal physics
if !place_meeting(x-1, y, objSolid)
global.xspeed = walkSpeed;
}
else
{
//Ice physics
if !place_meeting(x-1, y, objSolid)
global.xspeed += iceDecWalk;
}
image_xscale = abs(image_xscale);
if canSpriteChange == true
{
sprite_index = sprWalk;
image_speed = 0.15;
}
}
}
else
{
if !(place_meeting(x, y+1, objIce) && global.xspeed != 0)
{
//Normal physics
global.xspeed = 0;
canInitStep = true;
}
else
{
//Ice physics
if global.xspeed > 0
global.xspeed -= iceDec;
else if global.xspeed < 0
global.xspeed += iceDec;
if global.xspeed > -iceDec && global.xspeed < iceDec
global.xspeed = 0;
}
if keyboard_check(vk_left) && !keyboard_check(vk_right)
image_xscale = -abs(image_xscale);
else if keyboard_check(vk_right) && !keyboard_check(vk_left)
image_xscale = abs(image_xscale);
if canSpriteChange == true
{
sprite_index = sprStep;
image_speed = 0;
}
}
}
else
{
canInitStep = false;
isStep = false;
if canSpriteChange == true
sprite_index = sprJump;
if keyboard_check(vk_left) && !keyboard_check(vk_right) && !place_meeting(x-1, y, objSolid)
{
global.xspeed = -walkSpeed;
image_xscale = -abs(image_xscale);
}
else if keyboard_check(vk_right) && !keyboard_check(vk_left) && !place_meeting(x+1 + (prevXScale == -64/500), y, objSolid) //For some reason, while on the left of the wall and facing left, then jumping and holding right would clip you through it. Prevented by checking if the player was facing left on the previous frame, and if so, disallow Mega Man to move if 2 pixels away from the wall instead of 1
{
global.xspeed = walkSpeed;
image_xscale = abs(image_xscale);
}
else
{
global.xspeed = 0;
if keyboard_check(vk_left) && !keyboard_check(vk_right)
image_xscale = -abs(image_xscale);
else if keyboard_check(vk_right) && !keyboard_check(vk_left)
image_xscale = abs(image_xscale);
}
}
}
else if canSpriteChange == true
{
//Even if canMove is false, we should still be able to change sprites
if ground == true
{
if global.xspeed == 0
{
sprite_index = sprStep;
image_speed = 0;
}
else
{
sprite_index = sprWalk;
image_speed = 0.15;
}
}
else
{
sprite_index = sprJump;
}
}
//Sidestepping
if isStep == true
{
if !place_meeting(x+image_xscale * 500/64, y, objSolid)
global.xspeed = stepSpeed * image_xscale * 500/64;
if canSpriteChange == true
sprite_index = sprStep;
stepTimer += 1;
if stepTimer >= stepFrames
{
isStep = false;
stepTimer = 0;
}
}
//Allow movement
x += global.xspeed;
y += global.yspeed;
//Stop movement at section borders
if x > sectionRight-6 && !place_meeting(x+6, y, objSectionArrowRight) && !place_meeting(x-global.xspeed, y, objSectionArrowRight)
{
x = sectionRight-6;
global.xspeed = 0;
}
else if x < sectionLeft+6 && !place_meeting(x-6, y, objSectionArrowLeft) && !place_meeting(x-global.xspeed, y, objSectionArrowLeft)
{
x = sectionLeft+6;
global.xspeed = 0;
}
if y < sectionTop-32
y = sectionTop-32;
//Stop movement at room borders
if x > room_width-6
x = room_width-6;
else if x < 6
x = 6;
if y < -32
y = -32;
//Jumping
if canMove == true && ground == true && keyboard_check_pressed(ord("Z")) && !keyboard_check(vk_down)
{
canSpriteChange = true;
global.yspeed = -currentJumpSpeed;
ground = false;
y -= 10; //To negate the prevGround y += 1
sprite_index = sprJump;
}
//Minjumping (lowering jump when the jump button is released)
if ground == false && global.yspeed < 0 && !keyboard_check(ord("Z")) && canMinJump == true
{
canMinJump = false;
global.yspeed = 0;
}
//Climbing
var ladder = collision_rectangle(sprite_get_xcenter()-3, bbox_top, sprite_get_xcenter()+3, bbox_bottom-1, objLadder, false, false);
var ladderDown = collision_rectangle(sprite_get_xcenter()-3, bbox_bottom+1, sprite_get_xcenter()+3, bbox_bottom+2, objLadder, false, false);
if (((ladder >= 0 && keyboard_check(vk_up) && !keyboard_check(vk_down))
|| (ladderDown >= 0 && ground == true && keyboard_check(vk_down) && !keyboard_check(vk_up) && !place_meeting(x, y, objLadder)))
&& canMove == true)
{
climbing = true;
canMove = false;
canSpriteChange = false;
canGravity = false;
global.xspeed = 0;
global.yspeed = 0;
if ladder >= 0
{
x = ladder.x + 32;
}
else if ladderDown >= 0
{
x = ladderDown.x + 32;
y += climbSpeed;
ground = false;
}
sprite_index = sprClimb;
image_speed = 0;
ladderXScale = image_xscale;
}
//While climbing
if climbing == true
{
isStep = false;
canInitStep = false;
//Movement
if keyboard_check(vk_up) && !keyboard_check(vk_down)
{
climbSpriteTimer += 1;
global.yspeed = -climbSpeed;
}
else if keyboard_check(vk_down) && !keyboard_check(vk_up)
{
climbSpriteTimer += 1;
global.yspeed = climbSpeed;
}
else
{
global.yspeed = 0;
}
if climbSpriteTimer >= 32 && sprite_index == sprClimb
{
climbSpriteTimer = 0;
image_xscale = -image_xscale;
}
//Getup sprite
if !position_meeting(x, bbox_top+1, objLadder) && position_meeting(x, bbox_bottom+1, objLadder) //The second check is to make sure the getup animation is not shown when on the BOTTOM of a ladder that's placed in the air
{
sprite_index = sprGetup;
}
else
{
sprite_index = sprClimb;
}
//Releasing the ladder
if (ground == true && !keyboard_check(vk_up))
|| (keyboard_check_pressed(ord("Z")) && !keyboard_check(vk_up))
|| !position_meeting(x, bbox_top+43, objLadder)
|| !place_meeting(x, y, objLadder)
|| (keyboard_check(vk_down) && place_meeting(x, bbox_bottom+1, objTopSolid))
{
climbing = false;
canMove = true;
canSpriteChange = true;
canGravity = true;
image_xscale = ladderXScale;
global.yspeed = 0;
if position_meeting(x, bbox_bottom+15, objTopSolid) || ground == true
{
if !ground
{
y = floor(y);
while !place_meeting(x, y + 1, objTopSolid) && y < y + 2
{
y += 1;
}
ground = true;
}
if (keyboard_check(vk_right) && !keyboard_check(vk_left)) || (keyboard_check(vk_left) && !keyboard_check(vk_right))
{
sprite_index = sprWalk;
if keyboard_check(vk_right)
{
global.xspeed = walkSpeed;
image_xscale = 64/500;
}
else if keyboard_check(vk_left)
{
global.xspeed = -walkSpeed;
image_xscale = -abs(image_xscale);
}
}
else
sprite_index = sprStep;
}
else
sprite_index = sprJump;
if !position_meeting(x, bbox_top+43, objLadder)
{
y -= 16;
// Ensure ground is checked after adjusting y position
if place_meeting(x, y+1, objSolid) || place_meeting(x, y+1, objTopSolid)
{
ground = true;
sprite_index = sprStep;
}
}
}
}
//Water
if place_meeting(x, y, objWater) && inWater == false
{
inWater = true;
playSFX(sfxSplash);
var currentWater;
currentWater = instance_place(x, y, objWater);
instance_create(x, currentWater.bbox_top+1, objSplash);
}
if inWater == true
{
currentGrav = gravWater;
currentJumpSpeed = jumpSpeedWater;
bubbleTimer += 1;
if bubbleTimer >= 10
{
bubbleTimer = 0;
if !instance_exists(objAirBubble)
instance_create(x, y, objAirBubble);
}
}
else
{
currentGrav = grav;
currentJumpSpeed = jumpSpeed;
bubbleTimer = 0;
}
//Leaving the water
if inWater == true
{
var wtr;
wtr = instance_place(x, y-global.yspeed, objWater);
if wtr >= 0
{
if bbox_bottom < wtr.bbox_top
{
instance_create(x, wtr.bbox_top+1, objSplash);
inWater = false;
playSFX(sfxSplash);
}
}
}
//Gravity
if ground == false && canGravity == true
{
global.yspeed += currentGrav;
if global.yspeed > maxVspeed
global.yspeed = maxVspeed;
}
//Variables on the previous frame
prevGround = ground;
prevXScale = image_xscale;
}
To implement a Box object that the player can pick up and put down, we'll follow these steps:
Create the Box Object (objBox):
Define its properties and behaviors.
Modify the Player Object:
Add functionality to detect and interact with the box.
Handle picking up and putting down the box.
Handle Box Movement with the Player:
Ensure the box follows the player while being carried.
Ensure Proper Collision Handling:
Prevent placing the box in invalid locations.
Below is the detailed implementation using GameMaker Language (GML) based on the provided playerCollision and playerStep functions.
1. Creating the Box Object (objBox)
Create Event
Initialize any necessary variables for the box.
gml
// objBox: Create Event
isHeld = false; // Indicates if the box is being carried
heldBy = noone; // Reference to the player instance holding the box
Step Event
Handle any box-specific behavior. For simplicity, the box remains static unless picked up.
gml
// objBox: Step Event
if (isHeld && instance_exists(heldBy)) {
// Position the box relative to the player
// Adjust the offset as needed
x = heldBy.x + heldBy.image_xscale * 32; // 32 is half the player's width assuming 64px width
y = heldBy.y - heldBy.sprite_get_height(heldBy.sprite_index) / 2;
}
Draw Event (Optional)
Customize how the box is drawn if needed. Otherwise, the default sprite rendering suffices.
gml
// objBox: Draw Event
draw_self(); // Draw the box sprite
2. Modifying the Player Object
We'll integrate the box-picking functionality into the player's playerStep function. Additionally, we'll manage variables related to holding the box.
Add Variables in Create Event
Ensure the player has variables to track holding status.
/// @function playerStep
/// @description Handles general step event code for the player
function playerStep() {
// Existing code...
// --------------------------------------------------
// Box Interaction Logic
// --------------------------------------------------
// Define the interaction key, e.g., "X" key
var interactKey = ord("X");
// Check if the player presses the interact key
if (keyboard_check_pressed(interactKey)) {
if (!carryingBox) {
// Attempt to pick up a box
var box = instance_nearest(x, y, objBox);
var pickupRange = 32; // Define how close the player needs to be to pick up the box
if (box != noone && point_distance(x, y, box.x, box.y) <= pickupRange) {
// Pick up the box
carryingBox = true;
heldBox = box;
box.isHeld = true;
box.heldBy = id; // 'id' refers to the current player instance
// Optional: Adjust player's sprite or animation to indicate carrying
}
} else {
// Attempt to put down the box
if (heldBox != noone) {
// Determine the drop position
var dropX = x + image_xscale * 40; // Adjust as needed
var dropY = y - sprite_get_height(sprite_index) / 2;
// Check for collision at the drop position
if (!place_meeting(dropX, dropY, objSolid) && !place_meeting(dropX, dropY, objTopSolid)) {
// Place the box
carriedBox.isHeld = false;
carriedBox.heldBy = noone;
carriedBox.x = dropX;
carriedBox.y = dropY;
// Update carrying state
carryingBox = false;
heldBox = noone;
} else {
// Optional: Notify the player that the drop location is invalid
show_debug_message("Cannot place the box here!");
}
}
}
}
// --------------------------------------------------
// Continue with existing playerStep code...
// --------------------------------------------------
// Handle carrying the box during movement
if (carryingBox && heldBox != noone) {
// The box's Step Event already positions it relative to the player
// Additional logic can be added here if needed
}
// Existing movement, gravity, collision, etc.
// Existing code ends...
}
Explanation of the Box Interaction Logic:
Interaction Key:
The "X" key (ord("X")) is chosen as the interaction key. You can change this to any preferred key.
Picking Up the Box:
When the player presses the interact key and is not already carrying a box, the game searches for the nearest objBox within a defined pickupRange.
If a box is found within range, it sets carryingBox to true and stores a reference to the box in heldBox.
The box's isHeld property is set to true, and heldBy points to the player instance, allowing the box to follow the player.
Putting Down the Box:
If the player is already carrying a box and presses the interact key again, the game attempts to place the box.
It calculates a dropX and dropY position relative to the player's current position.
Before placing, it checks for collisions to ensure the drop location is valid.
If valid, it updates the box's position and resets the carrying state.
Collision Checks:
Uses place_meeting to ensure the box isn't placed inside a solid object.
3. Handling Box Movement with the Player
The box's Step Event ensures it follows the player when being carried. Here's a more refined version to ensure smooth positioning:
gml
// objBox: Step Event
if (isHeld && instance_exists(heldBy)) {
var player = heldBy;
// Define offsets based on player's direction
var offsetX = player.image_xscale * 40; // 40 pixels to the side
var offsetY = -player.sprite_get_height(player.sprite_index) / 2; // Adjust vertically
// Smoothly follow the player (optional)
x = lerp(x, player.x + offsetX, 0.5);
y = lerp(y, player.y + offsetY, 0.5);
}
Explanation:
Offsets:
offsetX positions the box to the left or right of the player based on the player's facing direction (image_xscale).
offsetY vertically aligns the box with the player.
lerp Function:
The lerp function creates a smooth transition, making the box follow the player more naturally.
4. Ensuring Proper Collision Handling When Placing the Box
When attempting to put down the box, it's crucial to ensure that the drop location isn't obstructed. This is handled in the playerStep function's box interaction logic using place_meeting.
Handling Drop Constraints:
Solid Objects:
Boxes cannot be placed inside objects tagged as objSolid or objTopSolid.
Adjusting Drop Position:
The dropX and dropY can be adjusted based on game design to suit various scenarios (e.g., placing on floors, avoiding overlaps).
5. Optional Enhancements
Visual Indicators:
Highlighting Boxes:
When the player is near a box, you can highlight it to indicate it's interactable.
Carrying Animation:
Change the player's sprite or add an animation to show they're carrying a box.
Multiple Boxes:
Handling Multiple Boxes:
If your game has multiple boxes, ensure the interaction logic selects the nearest or a specific box.
Stacking or Limits:
Decide if the player can carry multiple boxes or only one at a time.
Sound Effects:
Feedback Sounds:
Play sounds when picking up or putting down boxes for better user feedback.
gml
// Example: Play sound when picking up a box
if (carryingBox && heldBox != noone && heldBox.isHeld) {
audio_play_sound(sndPickup, 1, false);
}
// Example: Play sound when putting down a box
if (!carryingBox && previouslyCarryingBox) {
audio_play_sound(sndPutdown, 1, false);
}
Complete Integration Example
Here's how the updated portions of your player object might look when integrating the box interaction:
gml
// Player Object: Create Event
carryingBox = false;
heldBox = noone;
// Player Object: Step Event
function playerStep() {
// --------------------------------------------------
// Existing player movement, collision, and physics code
// --------------------------------------------------
// --------------------------------------------------
// Box Interaction Logic
// --------------------------------------------------
var interactKey = ord("X");
if (keyboard_check_pressed(interactKey)) {
if (!carryingBox) {
// Attempt to pick up a box
var box = instance_nearest(x, y, objBox);
var pickupRange = 32;
if (box != noone && point_distance(x, y, box.x, box.y) <= pickupRange && !box.isHeld) {
carryingBox = true;
heldBox = box;
box.isHeld = true;
box.heldBy = id;
// Optional: Change sprite or animation
// sprite_index = sprCarry;
// Play pickup sound
audio_play_sound(sndPickup, 1, false);
}
} else {
// Attempt to put down the box
if (heldBox != noone) {
var dropX = x + image_xscale * 40;
var dropY = y - sprite_get_height(sprite_index) / 2;
// Check for collision at drop position
if (!place_meeting(dropX, dropY, objSolid) && !place_meeting(dropX, dropY, objTopSolid)) {
// Place the box
heldBox.x = dropX;
heldBox.y = dropY;
heldBox.isHeld = false;
heldBox.heldBy = noone;
// Update carrying state
carryingBox = false;
heldBox = noone;
// Optional: Change sprite or animation
// sprite_index = sprIdle;
// Play putdown sound
audio_play_sound(sndPutdown, 1, false);
} else {
// Optional: Notify invalid drop location
show_debug_message("Cannot place the box here!");
}
}
}
}
// Handle carrying the box
if (carryingBox && heldBox != noone) {
// The box's Step Event manages positioning
// Additional logic if necessary
}
// --------------------------------------------------
// Continue with the rest of the playerStep code
// --------------------------------------------------
// Existing movement, collision, gravity, etc.
// Variables on the previous frame
prevGround = ground;
prevXScale = image_xscale;
}
Summary
By following the above steps, you've successfully implemented a Box object that the player can pick up and put down within your game. This integration ensures smooth interaction between the player and the box, maintaining collision integrity and providing visual and auditory feedback to enhance the gameplay experience.
Feel free to further customize the behavior, such as adding animations, limiting the number of boxes a player can carry, or introducing different box types with unique properties.