Jump to content


Photo
* * * * * 13 votes

Smart Codes


  • Please log in to reply
379 replies to this topic

#1 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 09 March 2009 - 11:39 PM

  • Title: Smart Codes
  • Description: Collection of useful small scripts that are used over and over again.
  • GM Version: Gm7 (the gmk, the codes in the .rtf file are applicable to most versions.)
  • Registered: For the most part, no, but for some codes, yes. I will try to state when registered is required
  • File Type: .rtf with the compiled codes. .gmk which also contains the codes, in text form.
  • File Size: Very Small (less than 1 mb)
  • File Link: [Removed, redundant]
FIRST 10 CODES IN AN EXAMPLE Made by Jakyl11:
First_10_examples_gmk_made_by_Jakyl11
This is highly recommended, if your new to gml, and are having trouble implementing the codes.
Additional Info:

The content of those files can be found in the post below... but if you prefer to download it onto your hard-drive then download away. *OUTDATED* Will be updated hopefully soon

I'm hoping that you will share your 'smart' codes, which you use, so that they can be added to the list.

Here is the list of Smart Codes which I have compiled so far. Credit has been given, and please continue to contribute to the effort!

SMART CODES compiled by Desert Dog



CONTRIBUTED BY General Leo:

1. Custom alarms not using alarms (code rewritten by Pandaboy )
if timer >= 0 { timer -= 1; }
if timer == 0 {
 //do this
 //do this
 //do this
}
A close replicate to the built-in alarm system. Simply set timer to whatever value, and it'll
count down automatically until it reaches 0, where it will execute the code.
It will wait at -1 until you set it again.

You can use this if you want your own in-code alarm system, or if you simply need more than 12 alarms..!

2. Automatic adjusting screen
view_hborder=view_wview/2 -obj_player.sprite_width
view_vborder=view_hview/2 -obj_player.sprite_height
This is probably one of the best "smart codes" I know. It resets your view so that "obj_player" is always perfectly in the middle. If you have a game where the player's sprite changes sizes or shapes, all you gotta do is run this code once after it changes sprites and it is perfect every time! Just make sure you have views turned on.

3. Perfect landing (platformers)
if vspeed > 0 && !place_free(x,y+vspeed) 
move_contact(270)
vspeed = 0
You may notice in your platformer that when you land, your character stops just above the ground, before landing, then drops the last few pixels. It can get very annoying at times. Use this code on your character when he comes in contact with the ground. It tells GM the exact amount of downward speed it needs to land perfectly. You won't notice any difference other than landing will be nice and smooth.

4. Easy gravity (platformers)
if !instance_place(x,y+1,obj_Solid)
gravity=0.5
if instance_place(x,y+1,obj_Solid)
gravity=0
if vspeed>10
vspeed=10
This code helps because it creates gravity ONLY if there is space under you that doesn't have a solid object. It also limits your vertical speed which helps with falling through floor bugs. Lowering the number helps more but may make it look less realistic. Try using different limit amounts. Change obj_Solid to whatever object you use for your ground. It can be a parent object if you use more then 1 for your ground objects.

Shorter Platform gravity code. (variation of General Leo's code above,written by Noitora)
Instead of using,
if place_free(x,y+1)
gravity=gravity_amount // gravity_amount can be 0.5, or a variable
You can have this code
gravity=place_free(x,y+1)*gravity_amount
Replace gravity amount with the amount of gravity you want. (e.g. 0.5, 1, .2, variablename, etc.)
This is helpful for shortening code length.

5. Rotate / orbit object
spin+=10
x=obj_Player.x+lengthdir_x(obj_Player.sprite_width*1,spin)
y=obj_Player.y+lengthdir_y(obj_Player.sprite_height*1,spin)
This is a nifty little code that automatically makes the object go in circles around whatever object you put in the place of "obj_Player". It uses the objects sprite to find out how large of a circle it needs to make to go around it. Also, it will automatically jump into place so it doesn't matter where you create the rotating object in the room. It will jump into place and start rotating at the speed of the variable "spin" in this case. Just make sure this goes in your step event to keep it circling.

6. 360 degree turning
image_single=facing/10
facing = point_direction(x,y,mouse_x,mouse_y)
This is a very commonly used code for creating an object that can turn all the way around pointing toward the mouse at all times. It sets 1 subsprite (frame) for each direction. Works best when the sprite's first subsprite is facing right and the sprite has 36 frames and spinning counter clockwise. Now this code does that as well as makes the object face toward the mouse at all times. The 2nd line can be changed or taken out depending on where you want the object to face.

7. Setting a sprite as your font
Create:
global.SpecialFont=font_add_sprite(s_FontSprites,ord(' '),false,0)
Draw:
draw_set_font(global.SpecialFont)
draw_set_color(c_white)

I've seen a lot of people ask how to do this. This lets you make a sprite and use it when you use draw_text() instead of a normal font. You can name "SpecialFont" as whatever you want and set draw_set_color() as whatever color you want the text to be. (White makes it use the sprites actual colors) the "ord" you see tells it you have numbers, letters, and symbols included in your font. You can put "ord('0') and have frame 0 starting as the number 0 if you only want to have numbers. It took me quite a while to find the order game maker wants these to be in so I included one of the fonts I put together so you can know the order too. There may still be some more symbols I haven't found, but all the most common (and some of the lesser common) ones, I've already found for you.
And this is the example font sprite:
Posted Image


8. Good Healthbar
//DRAW:
draw_set_color(c_red) 
draw_line(x,y-10,x+linelength,y-10) 
if hpamount > hpmax hpamount = hpmax
if hpamount < 0 hpamount = 0
 
//STEP:
linelength= hpamount / hpmax * sprite_width
I've been asked many time on how to make a healthbar and many times the person wants it to only be so long even if it's a lot of HP. (just goes down slower...etc) Well this code does it all. This one uses a line which is smaller and cleaner looking rather then a rectangle. Just set hpamount, hpmax, and make sure linelength=0 is in create. Also be sure to put the first part of the code in draw and the second part in step. You can mess with the numbers like the 10s for the height (raise number to raise bar). Now you can set any objects health and not worry about line lengths! ;)


9. Room angling
view_angle[0]=-direction+90
image_angle=direction
This code is a little more advanced then you may think. It angles the entire room according to the object you put the code on (under step). Usually you'd want it on your main player which the view follows. This can give your game a really nice look but you must have a registered version of GM to do this.

CONTRIBUTED BY Raptor320/ND4SPD :

10: Push-off Collision
{
// in collision event with whatever object...
var_dir = point_direction(x,y,other.x,other.y)
x = x+lengthdir_x(-1,var_dir)
y = y+lengthdir_y(-1,var_dir)
}

Basically, what this code does is gently 'pushes' off the object your colliding with, in the shortest possible pathway! So if you get 'stuck' in an object, using this will kick you out of it, or if you have object always going on-top of each other, using this will keep them apart... In short, a VERY handy code. I like to use it with while(place_meeting(x,y,other))

CONTRIBUTED BY Games:
1:Move in a direction..
This moves the objects in a direction with a speed, without actually using direction and speed (it uses dir and spd ). This is good for pixel perfect collision checking, among other things.
x += lengthdir_x( spd, dir )
y += lengthdir_y( spd, dir )
2:Keep in the room..
This keeps an object (it must have a sprite) inside the room.
x = min( max( x, 0 + sprite_xoffset ), room_width + sprite_xoffset - sprite_width )
y = min( max( y, 0 + sprite_yoffset ), room_height + sprite_yoffset - sprite_height )
3:Change a variable..
This makes a message box pop up that lets you change the value of a variable. It automatically checks whether the variable is a string or a real value, so you won't get any complications changing something like gravity to a string.
if is_real( variable ) {
	variable = get_integer( "New Value?", variable ) }
else {
	variable = get_string( "New String?", variable ) }
4:Constrain distance to a point..
This snaps the object to a certain distance from a point. Very useful for 3d games, making the camera follow the player.
dir = point_direction( x, y, point.x, point.y )
x = point.x - lengthdir_x( dis, dir )
y = point.y - lengthdir_y( dis, dir )
5:Tween a variable to 0 (like friction)..
Pretty much tweens a variable down to 0. Instead of using 2 if statements, you can just use one line of code.
variable -= sign( variable ) * min( abs( variable ), .5 )
6:Random number between x and y..
Sets variable to a random number between x and y. You can set x and y as anything.. If it's 30 and 50, for example, it might set variable to 35 or 48.2, but never 56 and never 27.
variable = floor( random( y - x ) ) + x
7:Better game_end()
Just makes a pop-up, allowing the user to "cancel" exiting the game.
if show_message_ext("Exit?","YES","","NO") == 1 
	game_end();
8:The infamous isometric depth code..
This makes things nearer to the bottom of the room be drawn in front of things above them, emulating real-life depth.
depth = -y

Useful change of a Boolean value
variable = sign( variable - .5 )
//this will make 1 and 0 (Boolean) become a -1 and 1

variable = sign( variable + 1 )
//this will make a -1 and 1 into a Boolean

CONTRIBUTED BY daman123125: NOTE* Edited by Desert Dog
Better Game Save...
Simple, easy to use Save and Loading system, which can have as many save files as your computer can handle.
Saving code
file = get_save_filename("Game Files|*.sav;*","");
if string_length(file) >0  // if the user presses cancel, then it will return nothing.
{
game_save(file);	   // otherwise, save the game!
}

Loading code
file = get_open_filename("Game Files|*.sav;*","");
game_load(file);

Grid Drawing

Should be used in Draw Event. Draws a grid that fills up the whole room:
snapX=32; //change this to what 'snapx' you want
snapY=32; //change this to what 'snapy' you want
for (i=0; i<room_width; i+=snapX) 
   draw_line(i,0,i,room_height);
for (i=0; i<room_height; i+=snapY)
   draw_line(0,i,room_width,i);
The code is pretty straight forward, but if you're a little confused on how the' for' loop works, see the GM help manual.(which covers it very nicely)
CONTRIBUTED BY Steve III:
Here's a useful piece of code:

Creating instance with variables.

Say you want to create an instance with a Hp value of 'a'. Perform this code:
(instance_create(xxx,yyy,obj)).hp=a;

...and if you want to assign more variables or even perform a script use this:
obj=(instance_create(xxx,yyy,obj));
with (obj){
hp=a;
scr_action(arg0,arg1...);
}
Also, in with statements the keyword other refers to the object which called the with statement.

CONTRIBUTED BY DarkSentinel: Edited

Simple and Easy left/right movement
Put this code in the step event of the object, and when you press left/right, he'll move in that direction (Note: There is no collision checking)
hspeed = (keyboard_check(vk_right)-keyboard_check(vk_left))*5;
Eliminates the need for several ifs.
Explanation
I'll try to explain that code a bit. Basically, in code, a statement is either true, or false. The numerical value of true is 1, and false is 0. So, in the little code below, you will see an example of this.
keyboard_check(vk_right)  // if the key right is pressed, then the value 1 is returned. If it is NOT pressed, then 0 is returned.
Once you understand this, the above code makes more sense.. it's just simple maths.
hspeed = (keyboard_check(vk_right)-keyboard_check(vk_left))*5;
// is the same as 
hspeed=( (either 1 or 0 ) - (either 1 or 0 ) ) *5;
I hope this clears that up for you... ;)

*************
Faster drawn background

Hey, I just figured out a much faster way of drawing a background tiled in an area. Use d3d_draw_floor, it should be much faster than manually drawing it using two for loops :D. Problem is it only works with texture friendly backgrounds (dimensions must be a power of 2).
var col;
if (argument0 >= argument2) or (argument1 >= argument3)
{
  return(0);
}

col = draw_get_color();
draw_set_color(c_white);
d3d_draw_floor(argument0,argument1,0,argument2,argument3,0,
	background_get_texture(argument4),
	(argument2-argument0)/background_get_width(argument4),
	(argument3-argument1)/background_get_height(argument4));
draw_set_color(col);
return(1);
Remember to call this from a very deep object, or else it will draw it over other objects.

CONTRIBUTED BY CubinJ:

Clock like timer

I did manage to divulge a time code (e.g. 3:40) using Gen. Leo's Timer system a long time ago.
This is really long, so just take your time understanding it;
Room Start:
  minu = 5 //this is the variable for the minutes
  tsec = 0 //this is the variable for the tens digits of seconds
  sec = 0 //this is the variable for the ones seconds
  msec = 29 //this is the variable for milliseconds (basically room speed)

Step:
  if minu >= 0  //checks if there aren't any negative minutes...
	  {
	  if msec <= 34{ //This basically checks if the time is under a second (roomspeed)
	  msec+=1 //add a millisecond
		  if msec = 35{ //above, if it 34+1, it will = 35. Thus this if statement
		  msec=0 //reset the milliseconds
			  if sec=0{ //if the ones seconds have gone down to 0, e.g. 3:4 "0"
				  if tsec =0{ // and if the ten's seconds are at 0 e.g. 3: "0"0
				  sec=9 //set the ones seconds back to 9 (when you reach 0, you normally go back to 9)
				  minu -= 1 //subtract a minute
				  tsec=5 //set the tens seconds back to 5 (just like the seconds)
				  }
				  else if tsec != 0 && tsec <=5 //this statement will check the tens seconds before changing
				  { //e.g. 3:41 (tens must be between 1 and 5)
				  tsec-=1 //subtract a ten's second
				  sec =9 //reset the seconds back to 9
				  }
			  }
			  else if sec != 0 && sec <=9 // this statement will check the ones seconds
			  {
			  sec-=1 //subtract a ones second
			  }
		  }
	  }
  }
  /*Timer system: If there are 0-5 minutes on the clock;
  if a sec hasn't passed; keep the msec going;
  if the msec reach one sec;
  restart msec;
  subtract a sec */
End Step:
  if minu=0 && tsec=0 && sec=0
	  { // this statement checks if time is up
	  do this
	  do this
	  game_end()
	  }

This is how it would look in english.
/*Timer system: If there are 0-5 minutes on the clock;
  if a sec hasn't passed; keep the msec going;
  if the msec reach one sec;
  restart msec;
  subtract a sec */

CONTRIBUTED BY A saurus1:

Rotate sub-images forward or backwards

image_index+=((put an expression here, like (x==y))*2)-1;
This runs the image index backwards if the expression is false (adds -1), and forwards if the expression is true (adds 1). The *2-1 part is to change an out put of either 1 or 0 to 1 or -1.

Variable value swapping
y=x+y;
x=y-x;
y-=x;
Simple non-xor swapping algorithm that does not need a temporary variable, and x and y can be equal. Only works for numbers, though.


CONTRIBUTED BY Pinpickle:

Using Boolean values to save using 'if' statements

//Example of one way to use code
draw_set_color(c*c_blue)
//Another example
image_index=x>obj_player.x
//Another
gravity=place_free(x,y+1)/2
What all this does is shorten your code, instead of overly using ifs and elses, the code would normally be this.
//Example of one way to use code
if c draw_set_color(c_blue)
else draw_set_color(0)
//Another example
if x>obj_player.x image_index=1
else image_index=0
//Another
if place_free(x,y+1) gravity=0.5
else gravity=0
A time saver, and maybe saves the slightest insignificant amount of speed.

Pixel perfect collisions

h is the variable to replace hspeed
v is the variable to replace vspeed
var vv hh;
hh=1
vv=1
for(i=0;i<=max(abs(h),abs(v));i+=1){
					  if i<abs(h) && hh{
						 x+=place_free(x+sign(h),y)*sign(h)
						 h*=place_free(x+sign(h),y)
						 hh=place_free(x+sign(h),y)

					  }
					  if i<abs(v) && vv{
						 y+=place_free(x,y+sign(v))*sign(v)
						 v*=place_free(x,y+sign(v))
						 vv=place_free(x,y+sign(v))
					  }
}
This will move a pixel individually on each axis, then check if there is a collision.
Yes, I have tried converting h and v to a direction and speed type variable for even better collisions, but that didn't work...
At all.

NOTE: These variables are not affected by gravity, friction, etc. ...

Simple music system
Initiation in some control object (make sure this code is only executed once)
global.soundprev=/*insert beginning sound here*/
global.sound=/*insert beginning sound here*/
Step event for said control object
if !sound_isplaying(global.sound){
   sound_stop(global.soundprev)
   sound_play(global.sound)
}
Whenever you want to change the music
global.soundprev=global.sound
global.sound=/*insert new sound here*
Basically it's a music system that will work for basically any game, all you need is the two variables and you are on your way.

EASY DRAW SPRITE REGISTERED
draw_sprite_ext(sprite_index,image_index,x,y,image_xscale,imag
e_yscale,image_angle,image_blend,image_alpha)
This draws the sprite as if there were no draw event. Great to put in a script called draw_self and put it at the beginning of any draw event.
PRO REQUIRED!

EASY DRAW SPRITE UNREGISTERED *suggested by Bob_George33
This draws the sprite as if there were no draw event. Great to put in a script called draw_self and put it at the beginning of any draw event.
draw_sprite(sprite_index,image_index,x,y);

CONTRIBUTED BY Mark13673:

Here's my contribution...

1)For snapping to a 32x32 grid.
Change the numbers for other sizes (eg. 16,16,8) and the "+16" may be unnecessary depending on whether the origin of the sprite is in the center or at 0,0...
//argument1 = x coord
//argument2 = y coord
var dx,dy;
dx=round(argument0/32)*32+16;
dy=round(argument1/32)*32+16;
2) Short way to rotate toward direction
A lovely short way to make a sprite rotate towards a direction. Change the twelve to a higher number for faster and lower for slower...
image_angle=(image_angle+(sin(degtorad(direction-image_angle))*12));
3)Classic Boolean value change
This one is a classic for changing Boolean values (it is actually from Yourself)...
//This is the same as
//if variable=true then variable=false else variable=true;
variable=!variable;
4)Great wall sliding code
For all those that use speed/direction for movement in TDS games, here is a great wall sliding code. I usually put it in the players collision event with the wall object and it gives great results...
var xmot, ymot;
x=xprevious;
y=yprevious;
for (i=0; i<90; i+=5) //For even better results change the 5 to 1... But it can cause lag...
	{
	xmot=x+lengthdir_x(speed,direction+i);
	ymot=y+lengthdir_y(speed,direction+i);
	if !place_meeting(xmot,ymot,other){x=xmot;y=ymot;exit;}
	xmot=x+lengthdir_x(speed,direction-i);
	ymot=y+lengthdir_y(speed,direction-i);
	if !place_meeting(xmot,ymot,other){x=xmot;y=ymot;exit;}
	}

5)Natural paths using an mp_grid setup
Here is a complicated one that is great for creating natural paths with an mp_grid set up. It deletes all the unnecessary points on the path and results in a much more realistic path for an AI object or something...
var n,x1,y1,x2,y2,x3,y3;
if path_get_number(mypath)>2
	{
	for (n=1; n<path_get_number(mypath); n+=1)
		{
		x1=path_get_point_x(mypath,n-1)
		y1=path_get_point_y(mypath,n-1)
		x2=path_get_point_x(mypath,n)
		y2=path_get_point_y(mypath,n)
		x3=path_get_point_x(mypath,n+1)
		y3=path_get_point_y(mypath,n+1)
		if (x2-x1)*(y3-y2)=(x3-x2)*(y2-y1) 
			{
			path_delete_point(mypath,n)
			n-=1
			}
		}
	}
And I think that that is more than enough secrets for now!!!! I hope that this helps anybody reading the topic...

CONTRIBUTED BY [UTS]ShadowX:
Toggle idle/moving character

If your character has two separate sprites for standing still and moving, you can use this code to switch the sprites without using if statements. NOTE: This code is one line, but the forum makes it two on my screen.

sprite_index=max(s_run*(keyboard_check(vk_right)-keyboard_check(vk_left)>0),s_stand*(keyboard_check(vk_right)+keyboard_check(vk_left)==0));
Simply replace s_run with your moving character sprite and s_stand with the idle sprite, and change vk_right and vk_left to whatever keys you are using.

CONTRIBUTED BY chaz13

Average x and y values of objects

This find the average x and y values of the object in the with.
var xx,yy;

with(all){
xx+=x
yy+=y
}

xx/=instance_number(all)
yy/=instance_number(all)

CONTRIBUTED BY pixelpig: Edited and additions by Desert Dog

Open Website with GM lite

Also just incase any one doesnt know how to open a website with lite you should have this:
execute_shell("[Enter Website Address Here]","")
And an example would be...
execute_shell("http://www.yoyogames.com/","") // will open yoyogames

Send Email to me with GM lite
execute_shell('mailto:youremailaddress@whatever.com',0); // put your email address in :)

CONTRIBUTED BY ChaosKnighT:

Draw the object above all other instances:
// This has been tested, (in the step event), and behaves correctly
with(all) other.depth = min(depth,other.depth)+(id==other.id);
depth -= 1;

For centering the view on the object manually:

view_xview = min(max(x-view_wview/2,0),room_width-view_wview);
view_yview = min(max(y-view_hview/2,0),room_height-view_hview);

A script that takes that further... *suggested by Bob_George33 and re-written by brod*
Here is a simple script, which is just a slight extension of the one above. It limits the view area.
// move_view(view,object,minx,miny,maxx,maxy)
view_xview[argument0] = max(argument2,min(argument4-view_wview[argument0],argument1.x-(view_wview[argument0]/2)));
view_yview[argument0] = max(argument3,min(argument5-view_hview[argument0],argument1.y-(view_hview[argument0]/2)));
For smooth linear movement:

x = startx+(-cos(percent*pi)/2+0.5) *(endx-startx);
y = starty+(-cos(percent*pi)/2+0.5) *(endy-starty);
where startx, starty, endx, and endy are the start and end coordinates of the movement; and percent is a value from 0 to 1 that increments linearly.

for creating an object, then running code in it (this way is one line of code less than the one by steve III)
with(instance_create(obj,xx,yy)){
  //do stuff
}

CONTRIBUTED BY MegaManFan1: edited

Easy Password system
a=get_string("Enter Password","Password Here") // get user input, and store in the var a
Oke="Password Name"		// this line initialises the password.
if a=Oke	 
{					// did the user input the password?
//do this (something like room_goto() maybe, but otherwise, whatever cheat you want!)
}
The Code's well commented, and shouldn't need much explaining. :GM045:

CONTRIBUTED BY Flexaplex

With a chance out of x
if (random(1) < probability) 
{
  return true;
}
note: it should be < not <=

Now if you assign probability = 1/5; it will have 1 in 5 chance of being true. If you set probability = 3/4; it will have a 3 in 4 chance of being true. For percentage you obviously just put the number over 100, eg setting probability = 67/100; will give a 67% chance of true.

Toggle a variable between 2 values.

variable = tog0+tog1-variable;
For example to toggle a variable between the values 2 and 7 you would set it up like so:
var tog0, tog1;
tog0 = 2;
tog1 = 7;
variable = tog0+tog1-variable;
It works with negatives and Boolean (0,1) also. Of course variable = !variable is better for Boolean values still.

Code to set sprites to correct left/right direction in platformer (in step event):

if (keyboard_check_pressed(vk_right)) {image_xscale = +1;}
if (keyboard_check_pressed(vk_left))  {image_xscale = -1;}
Move Left/Right after player
In some games you may wish to move directly left/right depending on whether is left/right of you. For example:

if (x < obj_player.x)
{
  x += move_speed;
}
if (x > obj_player.x)
{
  x -= move_speed;
}
This code can be replaced instead by:

x += move_speed*sign(obj_player.x-x);

For easy topdown collision code I actually prefer this (step event):

if (keyboard_check(vk_right))  {if !(place_meeting(x+movement,y,obj_block)) {x += movement;}}
if (keyboard_check(vk_left))   {if !(place_meeting(x-movement,y,obj_block)) {x -= movement;}}
if (keyboard_check(vk_up))	 {if !(place_meeting(x,y-movement,obj_block)) {y -= movement;}}
if (keyboard_check(vk_down))   {if !(place_meeting(x,y+movement,obj_block)) {y += movement;}}

Good easy pushing blocks code

(collision event with push able block):
var x_hit,y_hit,side;
x_hit = x; y_hit = y;
x = xprevious; y = yprevious;
other.solid = true;
move_contact_solid(point_direction(x,y,x_hit,y_hit),point_distance(x,y,x_hit,y_hit));
other.solid = false;
	 if (bbox_left > other.bbox_right) {other.x -= push_amount; x -= push_amount; hspeed = 0;}
else if (bbox_bottom < other.bbox_top) {other.y += push_amount; y += push_amount; vspeed = 0;}
else if (bbox_right < other.bbox_left) {other.x += push_amount; x += push_amount; hspeed = 0;}
else if (bbox_top > other.bbox_bottom) {other.y -= push_amount; y -= push_amount; vspeed = 0;}

Snapping to an isometric grid:

var m, n;
m = round(y/vsnap - x/hsnap);
n = round(y/vsnap + x/hsnap);
x = (n - m)/2*hsnap;
y = (n + m)/2*vsnap;

Simple good pause game script (works in any event):

io_clear();
while (true)
{
  if (keyboard_check_pressed(pausekey)) {break;}
  draw_text(x,y,"PAUSED");
  screen_refresh();
  io_clear();
  keyboard_wait();
  io_handle();
}

Cycle Variables
Using mod to cycle though a variable. eg instead of using:
current_weapon += 1;
if (current_weapon >= weapon_num)
{
  current_weapon = 0;
}
You can use:

current_weapon = (current_weapon+1) mod weapon_num;
To cycle backwards you need to use:

current_weapon = ((current_weapon-1 mod weapon_num) + weapon_num) mod weapon_num;

Checking if a number is a multiple of a value:

if (number mod value == 0)
{
  //then number is a multiple of value
}

CONTRIBUTED BY Bombshell edited by Desert Dog

If you use hspeed and image_xscale in a platform game, then pop this in the step event. *note, sprite faces right*
if hspeed != 0 {image_xscale=sign(hspeed);}

This is a lot shorter than,
if hspeed > 0
{image_xscale = 1
}
if hspeed < 0
{image_xscale = -1
}
The 'if hspeed != 0' check is necessary, because you don't want to set the image_xscale to 0, because then the sprite will disappear!

CONTRIBUTED BY MasGuitarHero
Here is one that calculates the right image_speed (mostly for things that walk), based on:
-Speed of the object
-Room Speed
-Number of sub images

image_speed=(image_number/room_speed)*speed

Its very helpful. This will pretty much eliminate the trial and error you would have to go through to find the perfect image_speed.

CONTRIBUTED BY brod
Grid-styled array drawing.
Instead of listing arrays as a big list, this code will list the arrays side-by-side as shown in the below e.g.

Val 1
Val 2
Val 3
Val 4

Into
Val 1 Val 2
Val 3 Val 4

for(i=0;i</*Array Size*/;i+=1) {
	draw_text(
	/*x off*/+(i mod /*cells per row*/)* /*space per col*/,
	/*y off*/+(i div /*cells per row*/)* /*space per row*/,
	/*array_name*/[i]);
}
The place for your respective values have been clearly marked off. If you would like to see some example values, and a slight explanation/example of use, then go here:
http://gmc.yoyogames...&...t&p=3137635

(Not limited to arrays, with some tweaking, you can draw a ds_list the same way using ds_list_size()!)
********************


*Note1: General Leo's codes come from his GML tutorial. (link below)
*Note2: The .rtf file will be updated as often as possible, but it will generally contain less codes than this post, as people will be posting codes between updates.

This is what I have so far, I hope this helps you, and if you have any smart codes, PLEASE post them!

Further Reading
First of all, I would like to recommend General Leo's GML Tutorial, from which the first Smart codes originated. In fact, if your a beginning programmer, and you haven't read it now, then do so!
Link: General Leo's GML Tutorial

Second: Pinpickle compiled a list of programming tips, and wot-nots. Good read, and if you have no idea how to program, this will point you down the right path.
Link: Pinpickle's Pit of Tips 'n' Stuff

Third: Flexaplex's Novice & Intermediate F A Q is highly recommened. Hmm, I'll say that again. Highly Recommended.... If you haven't read it.... Leave this topic and do it know!
Link: The Novice & Intermediate F A Q

Fourth: Games wrote a nice little tutorial, which pretty much consists of one little line.. I like to call it the ULTIMATE smart code.
Link: Games Tutorial

Fifth: xot has a beautiful website called 'GMLscripts.com', and, well, as the name implies, it has GML scripts. This is such a good read, and a lot of the codes/scripts are 'smarter' than codes in this list.
Link: GMLscripts.com

Sixth: If you missed the example, at the very top, then it's given again here: First_10_examples_gmk_made_by_Jakyl11
Thanks again, to Jakyl11 for making this. :)
Closing Comments

First, if you are a novice, and you find the above codes useful, and use them in the game, DO NOT CREDIT DESERT DOG. I only compiled the list.

If you want to credit someone, then credit the person contributed the code.

Second, Thank you to all who contributed to this list of Smart Codes! I hope that number increases, as you all contribute. ;)

Big thanks to Jakyl11 who took the time out to compile 10 of the first codes into a .gmk example. Thanks!

~DD

Edited by Desert Dog, 22 April 2012 - 02:37 AM.

  • 23

#2 Noitora

Noitora

    GMC Member

  • New Member
  • 29 posts

Posted 10 March 2009 - 01:15 PM

instead of the if place_free(x,y+1) then gravity=270...etc.

You can use gravity=place_free(x,y+1)*gravity_amount

Replace gravity amount with the amount of gravity you want.
It's been really helpful for me :)
  • 0

#3 Batch

Batch

    GMC Member

  • GMC Member
  • 728 posts

Posted 10 March 2009 - 02:00 PM

Well, I have to say that this is a rather amazing collection that you have here.
I did manage to divulge a time code (e.g. 3:40) using Gen. Leo's Timer system a long time ago.
This is really long, so just take your time understanding it; I hope that this counts as a smart code even though it's long?

Room Start:
  minu = 5 //this is the variable for the minutes
  tsec = 0 //this is the variable for the tens digits of seconds
  sec = 0 //this is the variable for the ones seconds
  msec = 29 //this is the variable for milliseconds (basically room speed)

Step:
  if minu >= 0  //checks if there aren't any negative minutes...
	  {
	  if msec <= 34{ //This basically checks if the time is under a second (roomspeed)
	  msec+=1 //add a millisecond
		  if msec = 35{ //above, if it 34+1, it will = 35. Thus this if statement
		  msec=0 //reset the milliseconds
			  if sec=0{ //if the ones seconds have gone down to 0, e.g. 3:4 "0"
				  if tsec =0{ // and if the ten's seconds are at 0 e.g. 3: "0"0
				  sec=9 //set the ones seconds back to 9 (when you reach 0, you normally go back to 9)
				  minu -= 1 //subtract a minute 
				  tsec=5 //set the tens seconds back to 5 (just like the seconds)
				  }
				  else if tsec != 0 && tsec <=5 //this statement will check the tens seconds before changing
				  { //e.g. 3:41 (tens must be between 1 and 5)
				  tsec-=1 //subtract a ten's second
				  sec =9 //reset the seconds back to 9
				  }
			  }
			  else if sec != 0 && sec <=9 // this statement will check the ones seconds
			  {
			  sec-=1 //subtract a ones second
			  }
		  }
	  }
  }
  /*Timer system: If there are 0-5 minutes on the clock; 
  if a sec hasn't passed; keep the msec going; 
  if the msec reach one sec; 
  restart msec; 
  subtract a sec */

End Step:
  if minu=0 && tsec=0 && sec=0
	  { // this statement checks if time is up
	  do this 
	  do this
	  game_end()
	  }


Hope this helps lol.
-CubinJ

Edited by CubinJ, 10 March 2009 - 02:01 PM.

  • 0

#4 A saurus1

A saurus1

    GMC Member

  • Sandbox Moderators
  • 1609 posts
  • Version:GM8.1

Posted 10 March 2009 - 04:03 PM

Here are my contributions:
This script allows you to bounce (not precisely) off an object, not just solid or all. Should be called in collision event.
#define move_bounce_object
/*
This script is very, very useful in any game, and even more so in platformers. This script makes it
possible for enemies to bounce off 'invisible' walls, while the character may pass through them.
Normally, using the move_bounce_all() function, one would get pretty bad results, because sometimes
there are multiple enemies on top of each other. By using this script, the object only bounces off
the desired object, the invisible wall. Of course, this is just one of the possibles with this script.
Use move_bounce_object(object)
object--id or index of the object being used to bounce off of.
Please note that this script does not work well with the receiving (the wall) object being set to precise
collision checking.

A saurus1
*/
if argument0.solid==true then {x+=hspeed; y+=vspeed;}
if !place_meeting(x,y,argument0) then exit;
var side,edge,cnt,xorig,yorig,xedge,yedge;
side=-1;
edge=false;
xorig=x;
yorig=y;
cnt=0;
//move object to edge of collision
while (place_meeting(x+lengthdir_x(-1,direction),y+lengthdir_y(-1,direction),argument0))
{
  x+=lengthdir_x(-1,direction);
  y+=lengthdir_y(-1,direction);
}
if cnt>=50 then {show_message("error finding edge of collision"); exit;}
xedge=x;
yedge=y;
//determine whether to bounce horizontally or vertically
if direction==90 or direction==270 
then side=1;
else side=0;
if direction<90 and direction>0
{
  if place_meeting(x-1,y-1,argument0)
  then side=1;
  else side=0;
}
if direction>90 and direction<180
{
  if place_meeting(x+1,y-1,argument0)
  then side=1;
  else side=0;
}
if direction>180 and direction<270
{
  if place_meeting(x+1,y+1,argument0)
  then side=1;
  else side=0;
}
if direction>270
{
  if place_meeting(x-1,y+1,argument0)
  then side=1;
  else side=0;
}
if side==0 then hspeed*=-1;
if side==1 then vspeed*=-1;
if side==-1 then {hspeed*=-1; vspeed*=-1; show_message("No collision!!!")}
if argument0.solid==false
{
x+=hspeed-abs(xorig-xedge);
y+=vspeed-abs(yorig-yedge);
}

Here is one that draws a spritebar but capped. It takes a sprite with three subimages, a cap for each end and a middle part to stretch.
#define draw_spritebar_capped
//this script draws a scaled bar with caps on both ends of x width, much like a healthbar with ends
//sprite must have 3 images: 1 image is the left side facing up, second is the right side facing up, and the last is the stretched part.
//The stretched part must fill all of the subimage
//The sprite used must have its origin at 0,0;
//if using a direction other than up, the box will be rotated around the top left corner
//use (sprite,length,x,y,direction,alpha)
//direction 0 to 3: 0=top is up, 3=top is left.

var w,sprw,dir;
dir=argument4*90 mod 360;
w=argument1;
sprw=sprite_get_width(argument0);
if argument1 < sprw*2 then w=sprw*2;
//draw the left cap
draw_sprite_ext(argument0,0,argument2,argument3,1,1,dir,c_whit
e,argument5);
//draw middle section
draw_sprite_ext(argument0,2,argument2+lengthdir_x(sprw,dir),argument3+lengthdir_y(sprw,dir),(1/sprw)*(w-2*sprw),1,dir,c_white,argument5);
//draw right cap
draw_sprite_ext(argument0,1,argument2+lengthdir_x(w-sprw,dir),argument3+lengthdir_y(w-sprw,dir),1,1,dir,c_white,argument5);

This one draws a sprite with bars of random alpha. Can be used for a hologram effect
#define draw_sprite_randbars
//define draw_sprite_randbars
//this script draws a sprite split into defined size bars, with each bar having a randomized alpha value.
//use (sprite,subimage,x,y,randomness,direction,thick
ness,alpha);
//for direction use 0=horizontal, 1=vertical.
//for randomness use 0=no variety in alpha, 10=most variety in alpha.
//thickness should be a factor of the sprite's width or height (depending or direction).
var i,r;
randomize();
r=min(argument4)/10;
if argument5==0
{
	for (i=0;i<sprite_get_height(argument0);i+=argument6;)
	{
		draw_sprite_part_ext(argument0,argument1,0,i,sprite_get_width(argument0),argument6,argument2,argument3+i,1,1,c_white,a
rgument7+random(2*r)-r);
		if i+argument6>=sprite_get_height(argument0) then break;
	}
}
else
{
	for (i=0;i<sprite_get_width(argument0);i+=argument6;)
	{
		draw_sprite_part_ext(argument0,argument1,i,0,argument6,sprite_get_h
eight(argument0),argument2+i,argument3,1,1,c_white,argument7+r
andom(2*r)-r);
		if i+argument6>=sprite_get_width(argument0) then break;
	}
}

Then this one calculates the percent of a collision between two objects (how much the object is over another object). This one has not been tested much, but I think it works.
#define scr_collision_percent
//this script returns the percentage of object1 that object2
//collides with if object1 is placed at position x,y. This will simply calculate
//the collisions between the whole sprites.
//use scr_collision_percent(object1,x,y,object2)
with (argument0)
{
	var xt,yt,rightt,bottomt,tobj,xm,ym,rightm,bottomm,xpe
r,yper,totalper;
	if !place_meeting(argument1,argument2,argument3)
	then return 0;
	tobj=instance_place(argument1,argument2,argument3);
	xt=argument3.x-argument3.sprite_xoffset
	yt=argument3.y-argument3.sprite_yoffset;
	rightt=xt+argument3.sprite_width;
	bottomt=yt+argument3.sprite_height;
	xm=x-sprite_xoffset;
	ym=y-sprite_yoffset;
	rightm=xm+sprite_width;
	bottomm=ym+sprite_height;
	//check for complete covering
	if xt < xm and yt <ym and rightt > rightm and bottomt > bottomm
	then return 1;
	//get the xpercent
	if rightt < rightm //my right edge is farther right than yours
	then xper+=(rightm-rightt)/sprite_width;
	if xm < xt //my left edge is farther left than yours
	then xper+=(xt-xm)/sprite_width;
	if bottomt < bottomt //my bottom edge is farther down that yours
	then yper+=(bottomm-bottomt)/sprite_height;
	if ym < yt //my top is above yours
	then yper+=(yt-ym)/sprite_height;
	totalper=(xper+yper)-(xper*yper); //this eliminates any overlap between the two
	return totalper;
}

These two scripts return the x/y coordinate of a point a given percentage between two points.
#define scr_getpercent_x
//this script returns the x coordinate of the position on given line at the given percentage along the line.
var d, r;
d=point_distance(argument0,argument1,argument2,argument3);
r=point_direction(argument0,argument1,argument2,argument3);
return argument0+lengthdir_x(d*argument4/100,r);

#define scr_getpercent_y
//this script returns the y coordinate of the position on given line at the given percentage along the line.
var d, r;
d=point_distance(argument0,argument1,argument2,argument3);
r=point_direction(argument0,argument1,argument2,argument3);
return argument1+lengthdir_y(d*argument4/100,r);

This script draws beams of light out from a given point. Set percent to 100, fade to 0, and the number of beams to a high number, and you get a full circle glow.
#define draw_beams_light
//this script draws 'block' beams of light in a circular array
//use (xcent,ycent,radius,beams,percent,color,fading,
rotation);
//xcent,ycent :: center of beams.
//radius :: radius of imaginary circle
//beams :: number of beams in circle
//percent :: percent (out of 100) of its section (circumference / beams) that any given beam occupies (taken out of center)
//color :: the color of the beams
//fading :: the beams are drawn with the current alpha at their base and alpha-fading at their end.
//rotation :: rotation of the beams (in degrees). Beams are drawn with one beam always on the 0 angle line unless rotated.
var beamprim,r,ps,anglediv,rot,i,myangle,curalpha,lx,l
y,rx,ry;
r=argument2;
ps=argument4/100;
rot=argument7;
anglediv=360/argument3;
curalpha=draw_get_alpha();
beamprim=draw_primitive_begin(pr_trianglelist);
//use for construction to repeat values for each of the beams
for (i=0;i<argument3;i+=1;)
{
	myangle=(i*anglediv+rot+360) mod 360;
	lx=argument0+lengthdir_x(r,(myangle+(anglediv/2)*ps+360) mod 360);
	ly=argument1+lengthdir_y(r,(myangle+(anglediv/2)*ps+360) mod 360);
	rx=argument0+lengthdir_x(r,(myangle-(anglediv/2)*ps+360) mod 360);
	ry=argument1+lengthdir_y(r,(myangle-(anglediv/2)*ps+360) mod 360);
	draw_vertex_color(argument0,argument1,argument5,curalpha); //center vertex
	draw_vertex_color(lx,ly,argument5,argument6); //draw left vertex
	draw_vertex_color(rx,ry,argument5,argument6); //draw right vertex
}
draw_primitive_end();

That's all
  • 0

#5 DarkSentinel

DarkSentinel

    GMC Member

  • New Member
  • 1965 posts

Posted 10 March 2009 - 06:53 PM

Some nice stuff, but most of them are scripts rather than smart codes.
Here's a simple one
hspeed = (keyboard_check(vk_right)-keyboard_check(vk_left))*5;
Eliminates the need for several ifs.
BTW what are the #s for in the above codes? Does it do anything in GM?
  • 0

#6 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 10 March 2009 - 11:49 PM

Thanks for contributing guys! And I hope this list helps you out.

@Noitora: Code added. Thanks!

@CubinJ: Code added, Pretty, neat. Maybe a bit long though?

@A saurus1: Your scripts are definitely too long, but I've added them because they are so cool!
Nevermind that crossed out bit.
@DarkSentinel: Code added, that's a really nifty little code!

Again, thankyou everybody, and I'm wondering, is anyone interested in compiling a list of 'Smart Scripts'? Then longer Codes like A saurus1's scripts, can go in it.

(Please, note: If you have a really cool script, don't hesitate to share it just because you think it will be too long!)

Cheers!

~DD

Edit: Fixed link to Pinpickles Tips.

Edited by Desert Dog, 11 March 2009 - 02:20 AM.

  • 0

#7 Batch

Batch

    GMC Member

  • GMC Member
  • 728 posts

Posted 11 March 2009 - 12:20 AM

Haha yeah. Just A BIT long :D

oh well. it's just basically a bunch of if statements lol.

and if you are too confused and don't want to read all of the timer's code, I suggest looking at this (english version, not gml :P):
/*Timer system: If there are 0-5 minutes on the clock; 
  if a sec hasn't passed; keep the msec going; 
  if the msec reach one sec; 
  restart msec; 
  subtract a sec */
And this "action" goes on until you reach 0:00 (check the End Step).

Thanks for adding mine :),
-CubinJ
  • 0

#8 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 11 March 2009 - 02:13 AM

Haha yeah. Just A BIT long ;)

oh well. it's just basically a bunch of if statements lol.

and if you are too confused and don't want to read all of the timer's code, I suggest looking at this (english version, not gml :P):

/*Timer system: If there are 0-5 minutes on the clock; 
  if a sec hasn't passed; keep the msec going; 
  if the msec reach one sec; 
  restart msec; 
  subtract a sec */
And this "action" goes on until you reach 0:00 (check the End Step).

Thanks for adding mine :D,
-CubinJ


Thanks for the explaination. I understood the code fine, but the explaination has now been added. Oh, and Thank YOU for contributing. :)

~DD

@Everyone in General: Post your Smart Codes!!! :P
  • 0

#9 Pinpickle

Pinpickle

    Abscure Programmer

  • GMC Member
  • 1353 posts

Posted 11 March 2009 - 06:35 AM

Okay, here is my smart code(s)

//Example of one way to use code
draw_set_color(c*c_blue)
//Another example
image_index=x>obj_player.x
//Another
gravity=place_free(x,y+1)/2
What all this does is shorten your code, instead of overly using ifs and elses, the code would normally be this.
//Example of one way to use code
if c draw_set_color(c_blue)
else draw_set_color(0)
//Another example
if x>obj_player.x image_index=1
else image_index=0
//Another
if place_free(x,y+1) gravity=0.5
else gravity=0
A time saver, and maybe saves the slightest insignificant amount of speed.


  • 0

#10 Sarah

Sarah

    GMC Member

  • New Member
  • 12 posts

Posted 11 March 2009 - 06:55 AM

Ooh, nice idea. Here's my input to the topic:

//changes a direciton to rotate towards another direction
//so di moves toward dir_to and returns the next step to get there
//argument0 = first direction
//argument1 = direciton to move to
//argument2 = will be the amount to turn
var di,dir_to;

dir=script(argument0);
dir_to=script(argument1);

if dir<dir_to
{
		if dir<dir_to-180 dir-=argument2;
		else dir+=argument2;
}
if dir>dir_to
{
		if dir>dir_to+180 dir+=argument2;
		else dir-=argument2;
}

if abs(dir-dir_to)<argument2
	dir=dir_to;
	
return dir;


//this will convert any number to a number 
//between 0 and 359, so -90 becomes 270
//argument0 = first direction

tt=argument0;

while(tt>=360)
{
	tt-=360;
}

while(tt<0)
{
	tt+=360;
}

return tt;

Basically what they do is make something rotate towards a point. Good for homing missiles or something.

Edited by Sarah, 11 March 2009 - 06:56 AM.

  • 0

#11 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 11 March 2009 - 06:55 AM

Thanks for these Pinpickle! *Added*
I especialy like this one...
draw_set_color(c*c_blue)

Edit: Ooooh, some more! Thanks Sarah! I'll work on adding those right away.

@Sarah: Code's added. Thanks!

Edited by Desert Dog, 11 March 2009 - 07:12 AM.

  • 0

#12 A saurus1

A saurus1

    GMC Member

  • Sandbox Moderators
  • 1609 posts
  • Version:GM8.1

Posted 11 March 2009 - 08:08 AM

image_index=x>obj_player.x

Oh, really? you can actually use comparison statements in variable assignments? (Yippeee :))
//this will convert any number to a number
//between 0 and 359, so -90 becomes 270
//argument0 = first direction

tt=argument0;

while(tt>=360)
{
	tt-=360;
}

while(tt<0)
{
	tt+=360;
}

return tt;
There is a faster way to do this. It's called the mod operator.
Speaking of which, here is another (short) code:
var dir;
dir=point_direction(x,y,argument0.x,argument0.y);
if abs(dir)<argument1 { image_angle=dir; exit; }
if (image_angle-dir+360) mod 360 < 180
then image_angle+=argument1;
else image_angle-=argument1;
This code can be used to turn turrets towards a player. Argument 0 is the object to track, argument 1 is how fast to turn.

Edited by A saurus1, 11 March 2009 - 08:20 AM.

  • 0

#13 Nocturne

Nocturne

    Nocturne Games

  • Administrators
  • 21298 posts
  • Version:GM:Studio

Posted 11 March 2009 - 05:49 PM

Here´s my contribution...

1)For snapping to a 32x32 grid. Change the numbers for other sizes (eg. 16,16,8) and the "+16" may be unnecessary depending on whether the origin of the sprite is in the center or at 0,0...
//argument1 = x coord
//argument2 = y coord
var dx,dy;
dx=round(argument0/32)*32+16;
dy=round(argument1/32)*32+16;

2)A lovely short way to make a sprite rotate towards a direction. Change the twelve to a higher number for faster and lower for slower...
image_angle=(image_angle+(sin(degtorad(direction-image_angle))*12));

3)This one is a classic for changing boolean values (it´s actually from Yourself)...
//This is the same as
//if variable=true then variable=false else variable=true;
variable=!variable;

4)For all those that use speed/direction for movement in TDS games, here is a great wall sliding code. I usually put it in the players collision event with the wall object and it gives great results...
var xmot, ymot;
x=xprevious;
y=yprevious;
for (i=0; i<90; i+=5) //For even better results change the 5 to 1... But it can cause lag...
	{
	xmot=x+lengthdir_x(speed,direction+i);
	ymot=y+lengthdir_y(speed,direction+i);
	if !place_meeting(xmot,ymot,other){x=xmot;y=ymot;exit;}
	xmot=x+lengthdir_x(speed,direction-i);
	ymot=y+lengthdir_y(speed,direction-i);
	if !place_meeting(xmot,ymot,other){x=xmot;y=ymot;exit;}
	}

5)Here´s a complicated one that is great for creating natural paths with an mp_grid setup. It delets all the unnecessary points on the path and results in a much more realistic path for an AI object or something...
var n,x1,y1,x2,y2,x3,y3;
if path_get_number(mypath)>2
	{
	for (n=1; n<path_get_number(mypath); n+=1)
		{
		x1=path_get_point_x(mypath,n-1)
		y1=path_get_point_y(mypath,n-1)
		x2=path_get_point_x(mypath,n)
		y2=path_get_point_y(mypath,n)
		x3=path_get_point_x(mypath,n+1)
		y3=path_get_point_y(mypath,n+1)
		if (x2-x1)*(y3-y2)=(x3-x2)*(y2-y1) 
			{
			path_delete_point(mypath,n)
			n-=1
			}
		}
	}

And I think that that is more than enough secrets for now!!!! I hope that this helps anybody reading the topic...
  • 0

#14 Pinpickle

Pinpickle

    Abscure Programmer

  • GMC Member
  • 1353 posts

Posted 11 March 2009 - 06:09 PM

Pixel perfect collisions anybody?

h is the variable to replace hspeed
v is the variable to replace vspeed

var vv hh;
hh=1
vv=1
for(i=0;i<=max(abs(h),abs(v));i+=1){
					  if i<abs(h) && hh{
						 x+=place_free(x+sign(h),y)*sign(h)
						 h*=place_free(x+sign(h),y)
						 hh=place_free(x+sign(h),y)

					  }
					  if i<abs(v) && vv{
						 y+=place_free(x,y+sign(v))*sign(v)
						 v*=place_free(x,y+sign(v))
						 vv=place_free(x,y+sign(v))
					  }
}
This will move a pixel individually on each axis, then check if there is a collision.
Yes, I have tried converting h and v to a direction and speed type variable for even better collisions, but that didn't work...
At all.

NOTE: These variables are not affected by gravity, friction, etc...


EDIT: Used my other smart code to optomize it, yes it all works very nicely.

Edited by Pinpickle, 11 March 2009 - 06:17 PM.

  • 0

#15 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 11 March 2009 - 11:17 PM

Whoa, some more great codes again! Thanks guys!

@A saurus: Extra code added, pretty neat, thanks!

@Mark13673: Whoa! You've posted some beauties! Big Thanks!

@Pinpickle: Pretty neat little script, added.

Thanks again everyone!

~DD
  • 0

#16 nick1965

nick1965

    GMC Member

  • New Member
  • 88 posts

Posted 12 March 2009 - 02:24 AM

This is a VERY good resource, everyone should bookmark it.

Umm, I could contribute something aswell, not very refined, check out my topic here to read more but basically it checks the syntax of a string before execute_string is ran, to prevent ugly error messages.

//str= str to check

str=argument0;






~Nick
  • 0

#17 nick1965

nick1965

    GMC Member

  • New Member
  • 88 posts

Posted 12 March 2009 - 02:29 AM

This is a VERY good resource, everyone should bookmark it.

Umm, I could contribute something aswell, not very refined, check out my topic here to read more but basically it checks the syntax of a string before execute_string is ran, to prevent ugly error messages.

//str= str to check
//bracket1 = number of "(" and brack2= ")"

var bracket1,bracket2;

str=argument0;

bracket1=string_count("(",str);
bracket2=string_count(")",str);

if bracket1!=bracket2{
SYNTAX IS WRONG!!!!!!!!!!
}

//end


For a full script with other features, go here: http://gmc.yoyogames...howtopic=417613

~Nick

Edited by nick1965, 12 March 2009 - 02:34 AM.

  • 0

#18 Nocturne

Nocturne

    Nocturne Games

  • Administrators
  • 21298 posts
  • Version:GM:Studio

Posted 12 March 2009 - 06:51 AM

Glad you like my codes DesertDog... Have you thought about compiling these in a pdf document and posting that instead of all the quotes? And I´d think about asking the mods to make this a sticky...
  • 0

#19 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 12 March 2009 - 08:14 AM

Glad you like my codes DesertDog... Have you thought about compiling these in a pdf document and posting that instead of all the quotes?

I'll look into doing a pdf document, but to be honest, I'm a little ignorant of such matters. Any help (links to how to do this..) would be greatly appreciated.

And Id think about asking the mods to make this a sticky...


Sorry, I don't understand.....

@nick1965: That code looks pretty interesting, but it's a little late now, so tomorrow I'll see about checking it out and adding it. Right now, could you possibly add a little more of an explaination/comment to the code? Thanks. :D

Edited by Desert Dog, 12 March 2009 - 08:15 AM.

  • 0

#20 Nocturne

Nocturne

    Nocturne Games

  • Administrators
  • 21298 posts
  • Version:GM:Studio

Posted 12 March 2009 - 09:21 AM

I mean that you should pm a mod and ask for them to include this in the pinned topics at the top of the page...
  • 0

#21 DarkSentinel

DarkSentinel

    GMC Member

  • New Member
  • 1965 posts

Posted 12 March 2009 - 01:25 PM

Hey, I just figured out a much faster way of drawing a background tiled in an area. Use d3d_draw_floor, it should be much faster than manually drawing it using two for loops :D . Problem is it only works with texture friendly backgrounds (dimensions must be a power of 2).
var col;
if (argument0 >= argument2) or (argument1 >= argument3)
{
  return(0);
}

col = draw_get_color();
draw_set_color(c_white);
d3d_draw_floor(argument0,argument1,0,argument2,argument3,0,
	background_get_texture(argument4),
	(argument2-argument0)/background_get_width(argument4),
	(argument3-argument1)/background_get_height(argument4));
draw_set_color(col);
return(1);
Remember to call this from a very deep object, or else it will draw it over other objects.
  • 0

#22 Chainsaw1337

Chainsaw1337

    GMC Member

  • New Member
  • 49 posts

Posted 12 March 2009 - 11:09 PM

Oops, bad post :/

-Chainsaw1337

Edited by Chainsaw1337, 12 March 2009 - 11:13 PM.

  • 0

#23 Dark Mario

Dark Mario

    GMC Member

  • New Member
  • 125 posts

Posted 12 March 2009 - 11:47 PM

This is a small piece of code to make a variable go towards zero even if it is negative.

variable-=sign(variable)*value

NOTE: use a negative value for value to make it further away from zero.

It is better than using:

if variable>0
  {
  variable-=value
  }
else
if variable<0
  {
  variable+=value
  }

This is my part.
Maybe I'll add more.

EDIT:typo

Edited by Dark Mario, 12 March 2009 - 11:51 PM.

  • 0

#24 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 13 March 2009 - 12:23 AM

I mean that you should pm a mod and ask for them to include this in the pinned topics at the top of the page...

Hmmm, you reckon? Maybe not now, I still have to do a lot of tidying up of typo's, and maybe after we get the codes in a .pdf, speaking of which, does anyone what to volunteer to put the codes in a .pdf? Or someother format? :snitch:

@nick1965: You code has now been added, looks interesting, by the way. Although I don't really see myself using it myself.

@DarkSentinel: You extra code has been added, and placed with your other code you contributed. Thanks again!

@Dark Mario: Nice code, nicely explained. Thankyou *Code added*

@Chainsaw: :lol:

Thanks again everybody! As noted, this is a community effort, and I'll be very happy if someone wants to volunteer to compile it in a .pdf, or whatever. I'm currently quite busy, so I wouldn't be able to do for at least a week. (I think)
  • 0

#25 Games

Games

    GMC Member

  • Banned Users
  • 2968 posts

Posted 13 March 2009 - 12:30 AM

Desert, I already contributed Dark Mario's code, but one that wont glitch out when you variable is almost 0. It will quite often never reach 0. He did explain it better, but having the same smart codes twice is bad.

Also, I'd like to suggest you limit the "complexity" of these scripts. This place is becoming a scripts sub-forum. This is for smart codes, which are small pieces of code that can save people a lot of time. Most of the larger scripts here are easy, just long and tedious, and thus belong in the scripts forum.

#26 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 13 March 2009 - 12:38 AM

Desert, I already contributed Dark Mario's code, but one that wont glitch out when you variable is almost 0. It will quite often never reach 0. He did explain it better, but having the same smart codes twice is bad.


Yeah, I see your point, but are your sure his code will glitch out? I will look into this, however. (soon)

Also, I'd like to suggest you limit the "complexity" of these scripts. This place is becoming a scripts sub-forum. This is for smart codes, which are small pieces of code that can save people a lot of time. Most of the larger scripts here are easy, just long and tedious, and thus belong in the scripts forum.


Originally, yes, this was meant for smaller codes... but who am I to not add very useful scripts, just because their, 'too long'? Sure, they aren't exactly what I was originally aiming for, and I would be very happy if someone else started a 'Smart Scripts topic, compiling all the codes which are too long for this one. But until then, the scripts stay. They ARE very useful, after all......

Note* This topic is still very much a WIP. So please post your your likes/dislikes, and I'll see what I can do about it. I won't get all angry if you point out typo's or grammer mistakes....

Oh, almost forgot, Thanks Games! Feedback like this is almost as important as the codes which are posted.

Edit: It should be noted that I had to edit one of your codes, Games.. you used show_message when it should have been show_message_ext, which made the code redundant. (sure, a simple enough mistake, easy to fix, but a beginner would have been totally stumped if the code hadn't worked....)

Please note everyone that my GML experience is not what it should be, and that you should test your own codes thorougly before posting them, as I may be unable to test all codes submitted. Especially considering that I'm unregisted

Edited by Desert Dog, 13 March 2009 - 12:42 AM.

  • 0

#27 Chainsaw1337

Chainsaw1337

    GMC Member

  • New Member
  • 49 posts

Posted 13 March 2009 - 12:39 AM

I guess I can compile it to a .pdf for ya.

-Chainsaw1337
  • 0

#28 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 13 March 2009 - 12:46 AM

I guess I can compile it to a .pdf for ya.

-Chainsaw1337


Thanks Chainsaw :snitch:. If you think any other format is more appropriate, then go ahead and use your discretion to use it.
  • 0

#29 Games

Games

    GMC Member

  • Banned Users
  • 2968 posts

Posted 13 March 2009 - 12:50 AM

Alright.

I think it would be wise to have a pro and lite gmk featuring all of their respective codes. I know that would take a bit of effort, but it would be quite helpful to those who are wondering what the codes actually do in a single editable without bloating it with other stuff. I might do it, through spring break.

#30 Desert Dog

Desert Dog

    GMC Member

  • GMC Member
  • 6409 posts
  • Version:Unknown

Posted 13 March 2009 - 12:59 AM

Alright.

I think it would be wise to have a pro and lite gmk featuring all of their respective codes. I know that would take a bit of effort, but it would be quite helpful to those who are wondering what the codes actually do in a single editable without bloating it with other stuff. I might do it, through spring break.

That would be so cool if you did that........

Edit: I'll probably be checking out all the codes I can anyway, so I could probably do the lite version one... (but you do yours anyway)

Edited by Desert Dog, 13 March 2009 - 01:00 AM.

  • 0




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users