Good evening, colleagues. The problem is the following: there is a 3D model that needs to be rotated with the front part depending on the location of the mouse: forward, backward, left, right. To rotate the model, the function returns the point to which the front of the model will be rotated. The image shows 4 zones, which, when hovered with the mouse, will set the direction. It is required to write a function that will determine two points x and z, depending on the location of the mouse cursor in any zone, i.e. if the mouse is in the upper zone, it should return a point with coordinates x = 0, z = 1. Below is my working piece of code, but I feel that it can be reduced to almost one line, but since I am not strong in mathematics, appeal to you.
function getStrictPointerPosition(pointerX: number, pointerZ: number): { x: number, z: number } {
let resultX: number = 0;
let resultZ: number = 0;
let absX: number = Math.abs(pointerX);
let absZ: number = Math.abs(pointerZ);
if (pointerX > 0 && pointerZ > 0) {
if (absX >= absZ) {
resultX = 1;
} else {
resultZ = 1;
}
} else if (pointerX < 0 && pointerZ > 0) {
if (absX >= absZ) {
resultX = -1;
} else {
resultZ = 1;
}
} else if (pointerX < 0 && pointerZ < 0) {
if (absX >= absZ) {
resultX = -1;
} else {
resultZ = -1;
}
} else {
if (absX >= absZ) {
resultX = 1;
} else {
resultZ = -1;
}
}
return {x: resultX, z: resultZ};
}
Tests cases
console.log(getStrictPointerPosition(2, -4)); // [0, -1]
console.log(getStrictPointerPosition(-2, -6)); // [0, -1]
console.log(getStrictPointerPosition(6, 2)); // [1, 0]
console.log(getStrictPointerPosition(8, -3)); // [1, 0]
console.log(getStrictPointerPosition(-5, 1)); // [-1, 0]
console.log(getStrictPointerPosition(-2, -1)); // [-1, 0]
console.log(getStrictPointerPosition(6, 2)); // [1, 0]
console.log(getStrictPointerPosition(8, -2)); // [1, 0]
console.log(getStrictPointerPosition(6, 6)); // [1, 0]
console.log(getStrictPointerPosition(-6, 6)); // [-1, 0]
console.log(getStrictPointerPosition(-6, -6)); // [-1, 0]
console.log(getStrictPointerPosition(6, -6)); // [1, 0]
When a point falls on one of the diagonals, no matter which of the two directions the function returns, for example, with input data x = 6, z = -6, the function can return both x = 0, z = -1, and x = 1, z = 0.
CodePudding user response:
If you can cast logical expression result to 0/1 integers in TypeScript
(I don't know but booleans are implemented as numerical values with a single binary digit (i.e., 0 & 1)
),
code might be very short:
def qu(x, z):
return -1 int(x>z) int(x>-z), -1 int(z>x) int(z>-x)
Alternative is ternary operator (x>z?1:0)