Jump to content
  • Advertisement
Sign in to follow this  

Rotating a line in Java

This topic is 2779 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey, I'm trying to rotate a line using 2d matrix rotation and have been getting some problems with negative values. The line appears to rotate by (the degree specified + 180) rather than purely the degree specified. I'm sure it's a pretty simple solution but I've been trying to work it out for about 2 hours now and am not anywhere nearer to a solution! If anyone could help me out it would be much appreciated!

Here is the code (it's in java, uses the acm library):

import acm.program.*;
import acm.graphics.*;
import java.lang.Math;

public class rotating_line extends GraphicsProgram {

GLine line;

private static final double degreesRotation = -5;

public void run() {

double difference = 300;

GPoint p1 = new GPoint(0, 0);
GPoint p2 = new GPoint(0, 500);

for (int i = 0; i < 19; i++) {

line = new GLine(p1.getX() + difference, p1.getY() + difference, p2.getX() + difference, p2.getY() + difference);

GLabel xLabel = new GLabel("x: " + Integer.toString((int)p2.getX()), getWidth() - 150, (i * 10) + 20);
GLabel yLabel = new GLabel("y: " + Integer.toString((int)p2.getY()), getWidth() - 50, (i * 10) + 20);

p2 = rotateLeft(degreesRotation, p1, p2, i);



public GPoint rotateLeft(double degreesRotation, GPoint p1, GPoint p2, int i) {

double degree = Math.toRadians(degreesRotation);

double dx = p1.getX() - p2.getX();
double dy = p1.getY() - p2.getY();

double xPos = p1.getX();
double yPos = p1.getY();

double x1 = (dx * Math.cos(degree)) - (dy * Math.sin(degree));
double y1 = (dx * Math.sin(degree)) + (dy * Math.cos(degree));

GLabel lx1 = new GLabel("x1: " + (int)x1, getWidth() - 350, (i * 10) + 20);
GLabel ly1 = new GLabel("y1: " + (int)y1, getWidth() - 250, (i * 10) + 20);

GPoint temp = new GPoint(x1 + xPos, y1 + yPos);

return temp;



edit: actually writing this post made me realise that it was rotating 180 degrees more than it should, so i have now solved the problem merely by asking for help. (changed this line: double degree = Math.toRadians(180+degreesRotation);)

post can be deleted!

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!