1. Hello Guest! It's with a heavy heart that we must announce the removal of the Legacy GMC Archive. If you wish to save anything from it, now's the time! Please see this topic for more information.
    Dismiss Notice

GMS 2 How to move relative to the mouse

Discussion in 'Programming' started by gamer_essence, Mar 1, 2018.

  1. gamer_essence

    gamer_essence Member

    Joined:
    Dec 2, 2016
    Posts:
    44
    So i have a character that moves but i want to move him in correspondance with the mouse. I.e. if you press w it moves toward the mouse and s it goes backwards. I also want to have it move left and right in correspondance with the mouse as well. I've tried for hours to figure this out and anything i do doesnt work so any help would be appreciated.
     
  2. TinCan

    TinCan Guest

    Just get the angle to the mouse and then use trig
    Code:
    angle = point_direction(x, y, mouse_x, mouse_y);
    max_speed = 5;
    
    if(keyboard_check(ord("W"))){
         x += max_speed * dcos(angle);
         y += max_speed * dsin(angle);
    }
    if(keyboard_check(ord("S"))){
         x -= max_speed * dcos(angle);
         y -= max_speed * dsin(angle);
    }
    
     
  3. JFitch

    JFitch Member

    Joined:
    Sep 28, 2016
    Posts:
    428
    Since Game Maker uses up as -y and down as +y, it may actually be this:
    Code:
    angle = point_direction(x, y, mouse_x, mouse_y);
    max_speed = 5;
    
    if(keyboard_check(ord("W"))){
         x += max_speed * dcos(angle);
         y -= max_speed * dsin(angle);
    }
    if(keyboard_check(ord("S"))){
         x -= max_speed * dcos(angle);
         y += max_speed * dsin(angle);
    }
    
     
  4. gamer_essence

    gamer_essence Member

    Joined:
    Dec 2, 2016
    Posts:
    44
    well this solves the forward and backward problem but what about left and right? It might be simple but i can not figure out how. The only way that i can think of is making it move 90 degrees from that direction but i dont know how
     
  5. JFitch

    JFitch Member

    Joined:
    Sep 28, 2016
    Posts:
    428
    Code:
    angle = point_direction(x, y, mouse_x, mouse_y);
    max_speed = 5;
    
    if(keyboard_check(ord("W"))){
        x += max_speed * dcos(angle);
        y -= max_speed * dsin(angle);
    }
    if(keyboard_check(ord("S"))){
        x -= max_speed * dcos(angle);
        y += max_speed * dsin(angle);
    }
    if(keyboard_check(ord("A"))){
        x -= max_speed * dsin(angle);
        y -= max_speed * dcos(angle);
    }
    if(keyboard_check(ord("D"))){
        x += max_speed * dsin(angle);
        y += max_speed * dcos(angle);
    }
     
    Guest User likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice