Stuyk

Code Snippets

Recommended Posts

Basically just post code snippets that you may find useful. Try to explain what it does and where it belongs. I'll start.

 

OnKeyDown function for Clientside to get exact string versions of keys.

// Bind all the keys available.
for(let i = 1; i <= 0xFE; i++) 
{ 
	mp.keys.bind(i, true, () => mp.events.call("keydown", i)); 
}

// Every time a key is pressed it gets sent to this event.
mp.events.add("keydown", (i) => {
    mp.gui.chat.push(String.fromCharCode(i)); // Use this to get the key in plain text.
});
  
// Credits to George since this is actually really freaking useful for non-cef based input.

 

  • Like 3

Share this post


Link to post
Share on other sites

Someone sent me a non-shit version of Screen2dToWorld3d:

Posting it here so it doesn't get lost.

const camera = mp.cameras.new("gameplay");

function screen2dToWorld3d(absoluteX, absoluteY) {
	const camPos = camera.getCoord();
	const { x: rX, y: rY } = processCoordinates(absoluteX, absoluteY);
	const target = s2w(camPos, rX, rY);

	const dir = sub(target, camPos);
	const from = add(camPos, mulNumber(dir, 0.5));
	const to = add(camPos, mulNumber(dir, 300));

	const ray = mp.raycasting.testPointToPoint(from, to, undefined, 287);

	return ray === undefined ? undefined : ray.position;
}

function s2w(camPos, relX, relY) {
	const camRot = camera.getRot(0);
	const camForward = rotationToDirection(camRot);
	const rotUp = add(camRot, new mp.Vector3(10, 0, 0));
	const rotDown = add(camRot, new mp.Vector3(-10, 0, 0));
	const rotLeft = add(camRot, new mp.Vector3(0, 0, -10));
	const rotRight = add(camRot, new mp.Vector3(0, 0, 10));

	const camRight = sub(rotationToDirection(rotRight), rotationToDirection(rotLeft));
	const camUp = sub(rotationToDirection(rotUp), rotationToDirection(rotDown));

	const rollRad = -degToRad(camRot.y);

	const camRightRoll = sub(mulNumber(camRight, Math.cos(rollRad)), mulNumber(camUp, Math.sin(rollRad)));
	const camUpRoll = add(mulNumber(camRight, Math.sin(rollRad)), mulNumber(camUp, Math.cos(rollRad)));

	const point3D = add(
		add(
			add(camPos, mulNumber(camForward, 10.0)),
			camRightRoll
		),
		camUpRoll);

	const point2D = w2s(point3D);

	if (point2D === undefined) {
		return add(camPos, mulNumber(camForward, 10.0));
	}

	const point3DZero = add(camPos, mulNumber(camForward, 10.0));
	const point2DZero = w2s(point3DZero);

	if (point2DZero === undefined) {
		return add(camPos, mulNumber(camForward, 10.0));
	}

	const eps = 0.001;

	if (Math.abs(point2D.x - point2DZero.x) < eps || Math.abs(point2D.y - point2DZero.y) < eps) {
		return add(camPos, mulNumber(camForward, 10.0));
	}

	const scaleX = (relX - point2DZero.x) / (point2D.x - point2DZero.x);
	const scaleY = (relY - point2DZero.y) / (point2D.y - point2DZero.y);
	const point3Dret = add(
		add(
			add(camPos, mulNumber(camForward, 10.0)),
			mulNumber(camRightRoll, scaleX)
		),
		mulNumber(camUpRoll, scaleY));

	return point3Dret;
}

function processCoordinates(x, y) {
	const { x: screenX, y: screenY } = mp.game.graphics.getScreenActiveResolution(0, 0);

	let relativeX = (1 - ((x / screenX) * 1.0) * 2);
	let relativeY = (1 - ((y / screenY) * 1.0) * 2);

	if (relativeX > 0.0) {
		relativeX = -relativeX;
	} else {
		relativeX = Math.abs(relativeX);
	}

	if (relativeY > 0.0) {
		relativeY = -relativeY;
	} else {
		relativeY = Math.abs(relativeY);
	}

	return { x: relativeX, y: relativeY };
}

function w2s(position) {
	const result = mp.game.graphics.world3dToScreen2d(position.x, position.y, position.z);

	if (result === undefined) {
		return undefined;
	}

	return new mp.Vector3((result.x - 0.5) * 2, (result.y - 0.5) * 2, 0);
}

function rotationToDirection(rotation) {
	const z = degToRad(rotation.z);
	const x = degToRad(rotation.x);
	const num = Math.abs(Math.cos(x));

	return new mp.Vector3((-Math.sin(z) * num), (Math.cos(z) * num), Math.sin(x));
}

function degToRad(deg) {
	return deg * Math.PI / 180.0;
}

function add(vector1, vector2) {
	return new mp.Vector3(vector1.x + vector2.x, vector1.y + vector2.y, vector1.z + vector2.z);
}

function sub(vector1, vector2) {
	return new mp.Vector3(vector1.x - vector2.x, vector1.y - vector2.y, vector1.z - vector2.z);
}

function mulNumber(vector1, value) {
	return new mp.Vector3(vector1.x * value, vector1.y * value, vector1.z * value);
}

exports = { screen2dToWorld3d };

 

Share this post


Link to post
Share on other sites

Get something to orbit around you or rotate around a specific area:

var angleInRadians: number = 0;
function getNewCameraPosition(distance: number) {
    if (angleInRadians > 180)
        angleInRadians = -180;

    if (angleInRadians < -180)
        angleInRadians = 180;

    var newAngle = 360.0 - ((angleInRadians + 360.0) % 360.0);
    var x = mp.players.local.position.x + distance * Math.sin(newAngle * Math.PI / 180.0);
    var y = mp.players.local.position.y + distance * Math.cos(newAngle * Math.PI / 180.0)
    var newPos = new mp.Vector3(x, y, mp.players.local.position.z);
    return newPos;
}

// Add += 1 to angleInRadians for speed / changes / etc.

 

Share this post


Link to post
Share on other sites

Get Chat Box Status:

var isChatOpen = toggle;

mp.events.add('render', () => {
if (mp.game.controls.isDisabledControlJustReleased(0, 245)) {
    if (isChatOpen)
         return;
    mp.gui.execute("const _enableChatInput = enableChatInput;enableChatInput = (enable) => { mp.trigger('chatEnabled', enable); _enableChatInput(enable) };");
    }
}

 

Share this post


Link to post
Share on other sites

Alt Tab for Client-Side. Kind of just a jimmy rig way to do it.

var altTabbed = false;

mp.events.add('render', () => {
// Alt Tab Helper
    if (altTabbed) {
        mp.game.graphics.drawRect(0.5, 0.5, 1, 1, 0, 0 ,0, 255);
        mp.game.graphics.drawText("Click to Tab Back In", [0.5, 0.5], {
            font: 4,
            centre: true,
            color: [255, 255, 255, 255],
            scale: [1.5, 1.5],
            outline: false
        });
        if (mp.game.controls.isDisabledControlJustPressed(0, 24)) {
            mp.game.graphics.transitionFromBlurred(1);
            altTabbed = false;
            mp.gui.chat.show(true);
            mp.game.ui.displayRadar(true);
            mp.game.ui.displayHud(true);
            return;
        }
        return;
    }
}

setInterval(() => {
    if (altTabbed)
        return;

    // Alt + Tab -> Toggle Screen Effect
    if ((mp.keys.isDown(18) && mp.keys.isDown(9)) || mp.keys.isDown(91)) {
        altTabbed = true;
        mp.gui.chat.show(false);
        mp.game.ui.displayRadar(false);
        mp.game.ui.displayHud(false);
    }
}, 100);

 

Share this post


Link to post
Share on other sites

Hi, Stuyk, have you ever used nativedb for GTA V development?  Since I developed with the nativedb, I changed your code to c++. I used a resolution of 1280 * 720, selected two points (640, 719) and (960, 540) on screen coordinate. Then I changed these two points to world 3d coordinates, drew a line between them in the GTA V game. However, I can not seen anything in the game. Here is my c++ code.

Vector3 screen2dToWorld3d(Camera cam, float screenX, float screenY)
{
	float relX, relY;
	processCoordinate(screenX, screenY, relX, relY);
	Vector3 target = s2w(cam, relX, relY);
	return target;
}

void processCoordinate(float screenX, float screenY, float &relX, float &relY)
{
	relX = -(1 - screenX / windowWidth * 2);
	relY = -(1 - screenY / windowHeight * 2);
}

Vector3 s2w(Camera cam, float relX, float relY)
{
	Vector3 camPos = CAM::GET_CAM_COORD(cam);
	Vector3 camRot = CAM::GET_CAM_ROT(cam, 0);
	Vector3 camForward = rotation2direction(camRot);
	Vector3 tmp;
	tmp.x = 10;
	tmp.y = 0;
	tmp.z = 0;
	Vector3 rotUp = addVector3(camRot, tmp);
	tmp.x = -10;
	Vector3 rotDown = addVector3(camRot, tmp);
	tmp.x = 0;
	tmp.z = -10;
	Vector3 rotLeft = addVector3(camRot, tmp);
	tmp.z = 10;
	Vector3 rotRight = addVector3(camRot, tmp);

	Vector3 camRight = subVector3(rotation2direction(rotRight), rotation2direction(rotLeft));
	Vector3 camUp = subVector3(rotation2direction(rotUp), rotation2direction(rotDown));

	float rollRad = -deg2rad(camRot.y);

	Vector3 camRightRoll = subVector3(mulNumber(camRight, cos(rollRad)), mulNumber(camUp, sin(rollRad)));
	Vector3 camUpRoll = addVector3(mulNumber(camRight, sin(rollRad)), mulNumber(camUp, cos(rollRad)));

	Vector3 point3D = addVector3(addVector3(addVector3(camPos, mulNumber(camForward, 10.0)), camRightRoll), camUpRoll);
	Vector3 point2D = w2s(point3D);
	if (point2D.x == -1)
	{
		return addVector3(camPos, mulNumber(camForward, 10.0));
	}
	
	Vector3 point3DZero = addVector3(camPos, mulNumber(camForward, 10.0));
	Vector3 point2DZero = w2s(point3DZero);
	if (point2DZero.x = -1)
	{
		return addVector3(camPos, mulNumber(camForward, 10.0));
	}

	float eps = 0.001;
	if (abs(point2D.x - point2DZero.x) < eps || abs(point2D.y - point2DZero.y) < eps)
	{
		return addVector3(camPos, mulNumber(camForward, 10.0));
	}

	float scaleX = (relX - point2DZero.x) / (point2D.x - point2DZero.x);
	float scaleY = (relY - point2DZero.y) / (point2D.y - point2DZero.y);

	return addVector3(addVector3(addVector3(camPos, mulNumber(camForward, 10.0)),
		mulNumber(camRightRoll, scaleX)), mulNumber(camUpRoll, scaleY));

}

Vector3 w2s(Vector3 position)
{
	Vector3 res;
	float x, y;
	if (!GRAPHICS::GET_SCREEN_COORD_FROM_WORLD_COORD(position.x, position.y, position.z, &x, &y))
	{
		res.x = res.y = res.z = -1;
		return res;
	}
	res.x = (x - 0.5) * 2;
	res.y = (y - 0.5) * 2;
	res.z = 0;
	return res;
}

Vector3 rotation2direction(Vector3 rotation)
{
	float z = deg2rad(rotation.z);
	float x = deg2rad(rotation.x);
	float num = abs((cos(x)));

	Vector3 direction;
	direction.x = -sin(z) * num;
	direction.y = cos(z) * num;
	direction.z = sin(x);
	return direction;
}

Vector3 addVector3(Vector3 vec1, Vector3 vec2)
{
	Vector3 res;
	res.x = vec1.x + vec2.x;
	res.y = vec1.y + vec2.y;
	res.z = vec1.z + vec2.z;
	return res;
}

Vector3 subVector3(Vector3 vec1, Vector3 vec2)
{
	Vector3 res;
	res.x = vec1.x - vec2.x;
	res.y = vec1.y - vec2.y;
	res.z = vec1.z - vec2.z;
	return res;
}

Vector3 mulNumber(Vector3 vec1, float value)
{
	Vector3 res;
	res.x = vec1.x * value;
	res.y = vec1.y * value;
	res.z = vec1.z * value;
	return res;
}

float deg2rad(float degree)
{
	return degree / 180 * PI;
}

And the sample drawing code:

float x1 = 640, y1 = 719, x2 = 960, y2 = 540;
Vector3 pos1 = screen2dToWorld3d(camera, x1, y1);
Vector3 pos2 = screen2dToWorld3d(camera, x2, y2);
GRAPHICS::DRAW_LINE(pos1.x, pos1.y, pos1.z, pos2.x, pos2.y, pos2.z, 255, 0, 255, 200);

 

Edited by yt1024

Share this post


Link to post
Share on other sites

I found that point2DZero.x was always -1, which meant point2Dzero undefined.

Oh no, it is so stupid that I used point2DZero.x = 1, rather than point2DZero.x == 1.

Thank you for your nice work.

Edited by yt1024

Share this post


Link to post
Share on other sites

I have another question now, using this function offline. For example, I can take a screen shot and save the camPos and camRot values, then I will do some work on this shot, finally I change the target 2D point on the shot to 3D world point. However, your method needs the online function world3dToScreen2d, which makes the offline transform impossible. I'd like to know if I can realize world3dToScreen2d offline ?

Share this post


Link to post
Share on other sites

I created a simple recursive function to get all files without needing to require them manually 

require("fs")
getFiles("./packages/server")

function getFiles(root, directory="") {
    fs.readdirSync(root+directory).forEach(file => {
        if (fs.statSync(`${root}${directory}/${file}`).isDirectory()) {
            getFiles(root, `${directory}/${file}/`)
        } else {
            if (file.endsWith(".js")) {
                if (directory) {
                    require(`.${directory}${file}`)
                } else {
                    require(`./${directory}${file}`)
                }
            }
        }
    })
}

 

  • Like 3

Share this post


Link to post
Share on other sites

Get Position in Front of Player

var playerPos = mp.players.local.position;
var xDistance = 1.3;
var yDistance = 1.3;

var newAngle = 360.0 - ((StartingRotation + 360.0) % 360.0);

var x = playerPos.x + xDistance * Math.sin(newAngle * Math.PI / 180.0);
var y = playerPos.y + yDistance * Math.cos(newAngle * Math.PI / 180.0);

var newPosition = new mp.Vector3(x, y, playerPos.z);

Runescape Based Experience Curve

double minLevel = 2;
double points = 0;

for (int level = 0; level < 100; level++)
{
  points += Math.Floor(level + 300 * Math.Pow(2, level / 7));
  if (level >= minLevel)
  {
    Console.WriteLine($"{level} -> XP: {Math.Floor(points / 4)}");
  }
}

 

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.