Search code examples
vectorlanguage-agnosticraytracingprojectile

How to do a Ray/Direction 2D system?


First of all, I'm sorry if my english isn't that great because I'm brazilian, so I'll try to describe my question decently.

Well, I'm developing a 2D tile-based game. Within the entities, I'm making a Projectile class. For now, the Projectile can move north/south/west/east, but I need to make it move to any direction. I've searched a bit but haven't found any good tutorials or examples about Ray 2D (only found about lighting ray-based).

For example:

x        
 \           x
  \         /
   \       /
    f     f

[x = projectile start position, f = projectile end position]

Supposing the projectile is consisted of X and Y (the width and height doesn't matter) and will move every tick, how can I achieve this?


Solution

  • I have no experience with lwjgl.

    However, it looks like a question of math to me. So if you know the distance and angle of the 'trajectory' you can convert from polar coordinates (distance, angle) to cartesian coordinates (x, y).

    The conversion is simple: x = distance * cos(angle) and y = distance * sin(angle). Then you simply need to add the x and y of the start coordinates.

    I recommend to play around with examples of processing to get a feeling for a solution in lwjgl.

    As a starter for processing you can use this snippet:

    //start coordinates
    float startx;
    float starty;
    
    //radius
    float r;
    //angle
    float theta;
    
    
    void setup() {
        size(640, 360);
        background(0);
    
       // Initialize all values
       startx = width/2;
       starty = height/2;
       r = random(startx);
       theta = -0.5;
    }
    
    void draw() {
        // Translate the origin point to the center of the screen
        translate(startx, starty);
    
       // Convert polar to cartesian
       float x = r * cos(theta);
       float y = r * sin(theta);
    
       // Draw the ellipse at the cartesian coordinate
       ellipseMode(CENTER);
       fill(200);
       ellipse(x, y, 12, 12);
    
       color c = #FFCC00;
       stroke(c);
       line(0,0,x,y);
    }