2

For a Minecraft project, I wanted to make the player face (0, 60, 0) gradually. So far, everything I have tried seems to fail when the player moves more than 720° around (0, 60, 0).

Anyone have an idea on how to make the camera move seamlessly to (0, 60, 0)?

Thank you!

Here is my code so far (that runs in a loop when toggled):

int x = 0;
int y = 60;
int z = 0;
        
player = Minecraft.getMinecraft().thePlayer;
        
double dirx = player.posX - 0;
double diry = player.posY - 60;
double dirz = player.posZ - 0;

double len = Math.sqrt(dirx*dirx + diry*diry + dirz*dirz);

dirx /= len;
diry /= len;
dirz /= len;

double pitch = Math.asin(diry);
double yaw = Math.atan2(dirz, dirx);

//to degree
pitch = pitch * 180.0 / Math.PI;
yaw = yaw * 180.0 / Math.PI;

yaw += 90f;
   
if(yaw > player.rotationYaw) {
    player.rotationYaw++;
} else if(yaw < player.rotationYaw) {
    player.rotationYaw--;
}

This code without the if statement works properly. The yaw and pitch variables are in degrees.

What I am having trouble with is the fact that whenever I turn around (0, 60, 0) for a few times, the screen suddenly does a 360° turn, for no apparent reason.

pppery
  • 3,731
  • 22
  • 33
  • 46
JustAJavaCoder
  • 47
  • 1
  • 10
  • Do you want to rotate from whatever direction the player is currently looking at? Is the position you want to look at a location in the world or relative to your player? Is `player.rotationYaw` in Degrees or Radians? – ManIkWeet Jun 20 '16 at 10:12
  • @ManIkWeet rotationYaw is in degrees, that I know for sure. – Pokechu22 Jun 20 '16 at 16:44
  • @ManIkWeet It is in degrees – JustAJavaCoder Jun 20 '16 at 20:47
  • @JustAJavaCoder Have you tried clamping the `rotationYaw` to `-180` <-> `180`? I don't understand what you mean with `the screen suddenly does a 360° turn, for no apparent reason.` as that wouldn't change anything visibly on your screen... – ManIkWeet Jun 21 '16 at 08:13

1 Answers1

1

This is a common problem. Or rather, the problem that people have commonly is they want to do "something across time" and don't know how to make it go "across time."

You need to lerp the camera a small distance each tick until the desired direction is achieved. You either need to:

a) create an event handler and subscribe to one of the TickEvents (pick an appropriate one, and then make sure to pick a phase, either Phase.START or Phase.END, or your code will run multiple times a frame).

b) in whatever method your code is already in (Note: this code must already be called once a tick) and do the lerping there.

Don't know how to calculate lerp? Stack Overflow already has that answered.

Community
  • 1
  • 1