This is a thread to post snippets of code that don't really fulfill the requirements for a full plugin.
Do not post questions about these snippets or any other JS related questions. They will be deleted. If you have questions, please create a new topic, with a link back to this one, in Plugin Support.
Do not post requests for snippets or other code. They will be deleted. If you have a request, we have a Plugin Request forum. Please post there. We want to keep this thread as clean as possible.
JS Snippets Thread
● ARCHIVED · READ-ONLY
-
-
Snippets by Archeia:
How to remove aliasing from RPG Maker MV Graphics Rendering
SpoilerCode:Graphics._centerElement = function(element) { var width = element.width * this._realScale; var height = element.height * this._realScale; element.style.position = 'absolute'; element.style.margin = 'auto'; element.style.top = 0; element.style.left = 0; element.style.right = 0; element.style.bottom = 0; element.style.width = width + 'px'; element.style.height = height + 'px'; element.style["image-rendering"] = "pixelated"; element.style["font-smooth"] = "none"; }; Sprite_Balloon.prototype.updateFrame = function() { var w = 32; var h = 24; var sx = this.frameIndex() * w; var sy = (this._balloonId - 1) * h; this.setFrame(sx, sy, w, h); };
Remove Page, PageUp and PageDn and replace it with Backspace from Name Input
SpoilerCode:// -- Disable Name Input Pages -- // Window_NameInput.LATIN1 = [ 'A','B','C','D','E', 'a','b','c','d','e', 'F','G','H','I','J', 'f','g','h','i','j', 'K','L','M','N','O', 'k','l','m','n','o', 'P','Q','R','S','T', 'p','q','r','s','t', 'U','V','W','X','Y', 'u','v','w','x','y', 'Z','[',']','^','_', 'z','{','}','|','~', '0','1','2','3','4', '!','#','$','%','&', '5','6','7','8','9', '(',')','*','+','-', '/','=','@','<','>', ':',';',' ','←','OK' ]; Window_NameInput.prototype.processOk = function() { if (this.character()) { this.onNameAdd(); } else if (this.isPageChange()) { this.processBack(); } else if (this.isOk()) { this.onNameOk(); } }; // -- Fix Name Input Font Display -- // Window_NameEdit.prototype.drawChar = function(index) { var rect = this.itemRect(index); this.resetTextColor(); this.drawText(this._name[index] || '', rect.x, rect.y, rect.width, 'center'); };
Change Critical Hit Formula
SpoilerCode:Game_Action.prototype.applyCritical = function(damage) { return damage * 2; };
Change Max Save File Slots
SpoilerCode:DataManager.maxSavefiles = function() { return 5; }; -
To use the following snippets, create a .js file in your plugins folder (the name will normally be shown, but in most cases doesn't matter), then add to your plugins.
Hide Destination Sprite
SpoilerCode:/*: * Hide Destination Sprite by Shaz * Ver 1.00 2018.04.01 * Shaz_HideDestinationSprite.js * * * @plugindesc Hide the flashing destination sprite on the map. * @author Shaz * * @help This plugin has no plugin commands * */ var Imported = Imported || {}; Imported.Shaz_HideDestinationSprite = true; var Shaz = Shaz || {}; Shaz.HDS = Shaz.HDS || {}; Shaz.HDS.Version = 1.00; (function() { Sprite_Destination.prototype.createBitmap = function() { var tileWidth = $gameMap.tileWidth(); var tileHeight = $gameMap.tileHeight(); this.bitmap = new Bitmap(tileWidth, tileHeight); //this.bitmap.fillAll('white'); this.anchor.x = 0.5; this.anchor.y = 0.5; this.blendMode = Graphics.BLEND_ADD; }; })();
Remove Autoshadows
SpoilerCode://============================================================================= // Remove Shadows (Shaz_RemoveShadows.js) // by Shaz // Last Updated: 2018.03.06 //============================================================================= /*: * @plugindesc Removes autoshadows * @author Shaz * * @help This plugin has no plugin commands. * */ var Imported = Imported || {}; Imported.Shaz_RemoveShadows = true; var Shaz = Shaz || {}; Shaz.RS = Shaz.RS || {}; Shaz.RS.Version = 1.00; (function() { var _Shaz_RS_DataManager_onLoad = DataManager.onLoad; DataManager.onLoad = function(object) { _Shaz_RS_DataManager_onLoad.call(this, object); if (object === $dataMap) { var indexStart = $dataMap.width * $dataMap.height * 4; var indexEnd = $dataMap.width * $dataMap.height * 5; for (var i = indexStart; i < indexEnd; i++) { $dataMap.data[i] = 0; } } }; })();
Disable Mouse Dashing (makes your PC walk at the same speed when using the mouse as when using the keyboard)
SpoilerCode:/*: * Slow Walking by Shaz * Ver 1.00 2018.03.07 * Shaz_SlowWalking.js * * * @plugindesc Makes player walk at normal speed when using mouse * @author Shaz * * * @help This plugin does not provide plugin commands. * */ var Imported = Imported || {}; Imported.Shaz_SlowWalking = true; var Shaz = Shaz || {}; Shaz.SW = Shaz.SW || {}; Shaz.SW.Version = 1.00; (function() { Game_Player.prototype.updateDashing = function() { if (this.isMoving()) { return; } if (this.canMove() && !this.isInVehicle() && !$gameMap.isDashDisabled()) { this._dashing = this.isDashButtonPressed(); } else { this._dashing = false; } }; })();
Pathfinding
SpoilerTo make an event (or the player) find their way to a certain location and stop when they get there, add a Set Movement Route set to repeat (optionally wait for completion) and add these two commands:
Code:where x and y, of course, are the coordinates you want them to move to. These could be numbers, formulae, or references to the x and y location of another event (though you might want to offset by one as the event likely won't be able to go ONTO the other event).Script: this.moveStraight(this.findDirectionTo(x, y)); Script: if (this.pos(x, y)) { this._moveRoute.repeat = false; }; -
This snippet allow you to: call a random color hex
PHP:can use in all element with tint.// get a random color function ranHexColors() { return ('0x' + Math.floor(Math.random() * 16777215).toString(16) || 0xffffff) }; -
This snippet allow you to: draw a easy customs graphics rectangles with radius.
PHP:// Build Rectangles // x, y, w:width, h:height, c:color, a:alpha, r:radius, l_c_a:[lineWidth,colorLine,alphaLine] function drawRec(x, y, w, h, c, a, r, l_c_a) { const rec = new PIXI.Graphics(); rec.beginFill(c||0xffffff, a||1); l_c_a && rec.lineStyle((l_c_a[0]||0), (l_c_a[1]||c||0x000000), l_c_a[2]||1); r && rec.drawRoundedRect(x, y, w, h, r) || rec.drawRect(x, y, w, h); return rec; };
ex: SceneManager._scene.addChild( drawRec(0, 0, 1310, 145) ); -
This snippet allow you to: get % for fit a sprite scale ratio locked in a bound (width,height).
PHP:ex:// Get a sprite ratio for scaling function getRatio(obj, w, h, set) { let r = Math.min(w / obj.width, h / obj.height); set && obj.scale.set(r,r); return r>1 && 1 || r; };
PHP:var picture = new Sprite(); picture.width = 99999; // pixel picture.height = 7589; // pixel var ratio = getRatio(picture,80,120); // get ratio for fit inside a [80,120] box picture.scale.set(ratio); -
Two ways of handling rolling multiple dice, such as in a damage formula:
This snippet adds a function to roll nDice of nSides each:
Code:function multiDice(nDice, nSides) { var totalRolled = 0; for (var i=0; i < nDice; i++) { totalRolled += Math.randomInt(nSides) + 1; return totalRolled; };
This snippet is embedded in another plugin, e.g. Hime's WeaponDamage, to interpret '#D#' or '#d#' text in a notetag and substitute the rolled value:
Code:(If you replace the constructed call of multiDice with that function's guts it won't roll new dice on each use of the weapon.)//weapon is passed-in notetag which is stripped of boundary text using // $.Regex = /<weapon[-_ ]damage>([\s\S]*?)<\/weapon[-_ ]damage>/im //defined in plugin code above this if (weapon.damageFormula === undefined) { weapon.damageFormula = "0"; var res = $.Regex.exec(weapon.note); if (res) { var diceRegex = /\s*(\d+)[dD](\d+)/m; var diceRes = diceRegex.exec(res[1]); var numDice, numSides, diceCall; while (diceRes) { numDice = diceRes[1]; numSides = diceRes[2]; diceCall = "multiDice("+numDice.toString()+","+numSides.toString()+")"; res[1] = res[1].replace(diceRegex, diceCall); diceRes = diceRegex.exec(res[1]); } weapon.damageFormula = res[1]; } } -
Multiple script events act as one big script event
This comes in two versions, and both should, in theory, fit in one script block, which means you don't even have to write a separate plugin for this.
This allows you to combine multiple script blocks into one, allowing you to continue code in the next script block. This means you can actually write functions within the event editor.
The first method is small. It essentially uses an eval to evaluate the script, pretty much like how RPG Maker MV itself does it.
Code:var script = ''; while(this.nextEventCode() === 355 || this.nextEventCode() === 655) { this._index++; script += this.currentCommand().parameters[0] + '\n'; } eval(script);
The second method is a bit longer, but does come with a slight performance boost, as it stores the script into a function object. This way, larger scripts don't have to constantly be recompiled. I can't however guarantee that it's as stable, though in theory, it should be stable.
Code:var script = '', current = this.currentCommand(); if(!current._reloader) { current._reloader = {index: 0}; while(this.nextEventCode() === 355 || this.nextEventCode() === 655) { this._index++; current._reloader.index++; script += this.currentCommand().parameters[0] + '\n'; } current._reloader.func = new Function(script); } else { this._index+= current._reloader.index; } current._reloader.func.call(this); -
This snippet allow you to: Zoom with scale and pivot map, based on memory point. Zoom compute with mouse position on screen.
PHP:// global for control zoom memory const memCoord = new PIXI.Point(); const memCoord2 = new PIXI.Point(); const TileMap = SceneManager._scene._spriteset._tilemap; // game map const Zoom = TileMap.scale; // zoom camera function wheel_Editor(event) { const pos = new PIXI.Point(mX,mY); TileMap.toLocal(pos, null, memCoord); // update before scale memory if(event.wheelDeltaY>0){ Zoom.x+=0.1,Zoom.y+=0.1 }else{ if(Zoom._x>0.3){ Zoom.x-=0.1, Zoom.y-=0.1 }; }; TileMap.toLocal(pos, null, memCoord2); // update after scale memory TileMap.pivot.x -= (memCoord2.x - memCoord.x); TileMap.pivot.y -= (memCoord2.y - memCoord.y); ScrollX -= (memCoord2.x - memCoord.x); // only if you use custom display system ScrollY -= (memCoord2.y - memCoord.y); }; document.addEventListener('wheel', wheel_Editor); -
Here are a few useful extra methods for the array class. Nothing fancy, just makes code look cleaner when you use then instead of manually writing the code.
PHP://============================================================================= // Array_util //============================================================================= (function() { //============================================================================= Array.prototype.includes = function(value) { return (this.indexOf(value) >= 0); }; Array.prototype.remove = function(value) { this.splice(this.indexOf(value), 1); }; Array.prototype.tryRemove = function(value) { var index = this.indexOf(value); if (index >= 0) { this.splice(index, 1); return true; } return false; }; //============================================================================= })(); -
I useful and experimental method for check out if is colliding with a circle form. I did this for my physic plugin (that I'm creating).
Code:/** * @author Dax|Kvothe * @contact http://dax-soft.weebly.com/ * @license MIT * @description This handles with the mathematical calculus to detect collisions * on a circle form. This is experimental. * @param {Body?} [a] will be the 'invasor'. * @param {Body?} [b] will be the reference for detect the collision * @param {Number} [radius] radius of the circle (general size) * @param {Number} [outline] by default is Math.E | See the list: * [Math.E|Math.LN10] => inside of circle. * [Math.PI] => increase a outline on circle by a "large" margin. * [Math.LN2|SQRT1_2] => inside of circle but need to pass over a 'large' margin. * [Math.LOG10E] => same as Math.LN2 but with a margin "more" 'big'. * [Math.LOG2E|Math.SQRT2] => Inside of circle but need to pass over a 'tiny' margin. * @returns {Boolean} */ const dcircle = function (a, b, radius, outline) { return ( ~~(Math.pow((a.x - (b.x - (1)) ), 2) + Math.pow((a.y - (b.y - (1)) ), 2)) <=Math.abs(((radius * ((a.width+a.height)/2)) * (outline || Math.E))) ); } -
Autosave:
(replace X with the save file ID #)
Code:$gameSystem.onBeforeSave(); if(DataManager.saveGame(X)) { StorageManager.cleanBackup(X); }
Autoload:
(replace X with the save file ID #)
Code:if(DataManager.loadGame(X)) { SoundManager.playLoad(); SceneManager._scene.fadeOutAll(); $gamePlayer.reserveTransfer($gameMap.mapId(), $gamePlayer.x, $gamePlayer.y); $gamePlayer.requestMapReload(); SceneManager.goto(Scene_Map); $gameSystem.onAfterLoad(); }
@Kvothe A useful thing to know with RPG Maker MV v1.6.0+ and the new NW.js we can use the ** operator now - no more Math.pow() !!
(a.x - (b.x - (1)) ) ** 2
@bblizzard Worth noting that we already have a native 'Array.prototype.includes' with the new NW.js version, it would be wise to not overwrite the native prototype. -
This snippet allow you to: List all files and folders in a directory with Node.js
PHP:var walkSync = function(dir, list) { var path = path || require('path'); var fs = fs || require('fs'), files = fs.readdirSync(dir), list = list || []; files.forEach(function(file) { // create instance for eatch folder if (fs.statSync(path.join(dir, file)).isDirectory()) { list = walkSync(path.join(dir, file), list); } else { list.push(path.join(dir, file)) }; }); return list; };
example
PHP:var walkSync = function(dir, list) { var path = path || require('path'); var fs = fs || require('fs'), files = fs.readdirSync(dir), list = list || []; files.forEach(function(file) { // create instance for eatch folder if (fs.statSync(path.join(dir, file)).isDirectory()) { list = walkSync(path.join(dir, file), list); } else { list.push(path.join(dir, file)) }; }); return list; }; const result = walkSync("SSA"); // scan folder named "SSA"result -
This snippet allow you to: Check collision between 2 obj.
PHP:function hitCheck(a, b){ var ab = a.getBounds(); var bb = b.getBounds(); return ab.x + ab.width > bb.x && ab.x < bb.x + bb.width && ab.y + ab.height > bb.y && ab.y < bb.y + bb.height; } -
This snippet allow you to: get full control and access of dom listener
PHP:var f = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function(type, fn, capture) { this.f = f; this.f(type, fn, capture); alert('Added Event Listener: on' + type); } function addListener() { var button = document.getElementById('button'); button.addEventListener('click', function() { alert('clicked') }, false); }
example;
You can for example check if listener exist or get scope.
Useful for mouse , sprite and events obj in rmmv
http://jsfiddle.net/jonforum/wyadov86/ -
Fix Name Input Font Display
Code:// -- Fix Name Input Font Display -- // Window_NameEdit.prototype.drawChar = function(index) { var rect = this.itemRect(index); this.resetTextColor(); this.drawText(this._name[index] || '', rect.x, rect.y, rect.width, 'center'); };
From this:
Spoiler
to this:
Spoiler -
Stop the cursor from blinking
SpoilerCode:// Stop the cursor from blinking Window.prototype._updateCursor = function() { this._windowCursorSprite.alpha = 255; this._windowCursorSprite.visible = this.isOpen(); };
Remove the white square when clicking on destination
SpoilerCode:// Remove White Square when clicking mouse destination Spriteset_Map.prototype.createLowerLayer = function() { Spriteset_Base.prototype.createLowerLayer.call(this); this.createParallax(); this.createTilemap(); this.createCharacters(); this.createShadow(); this.createWeather(); };
Add Shadows to Fonts in RPG Maker MV
SpoilerCode:// Add Shadows to Fonts in RPG Maker MV Bitmap.prototype._drawTextBody = function(text, tx, ty, maxWidth) { var context = this._context; context.fillStyle = this.textColor; context.shadowColor = 'rgba(76, 56, 70, 255)'; context.shadowBlur = 0; context.shadowOffsetX = 2; context.shadowOffsetY = 2; context.fillText(text, tx, ty, maxWidth); };
Make the Window Cursor Tile instead of Stretching
Use it with this plugin for maximum effect
SpoilerCode:// Make Cursor Tile Window.prototype._refreshCursor = function() { var pad = this._padding; var x = this._cursorRect.x + pad - this.origin.x; var y = this._cursorRect.y + pad - this.origin.y; var w = this._cursorRect.width; var h = this._cursorRect.height; var m = 4; var x2 = Math.max(x, pad); var y2 = Math.max(y, pad); var ox = x - x2; var oy = y - y2; var w2 = Math.min(w, this._width - pad - x2); var h2 = Math.min(h, this._height - pad - y2); var bitmap = new Bitmap(w2, h2); this._windowCursorSprite.bitmap = bitmap; this._windowCursorSprite.setFrame(0, 0, w2, h2); this._windowCursorSprite.move(x2, y2); // Spacing 1 var sp1 = 10; if (w > 0 && h > 0 && this._windowskin) { var skin = this._windowskin; var p = 96; var q = 48; bitmap.blt(skin, p, p, sp1, sp1, ox, oy); bitmap.blt(skin, p + q - sp1, p, sp1, sp1, ox + w2 - sp1, oy); bitmap.blt(skin, p, p + q - sp1, sp1, sp1, ox, oy + h2 - sp1); bitmap.blt(skin, p + q - sp1, p + q - sp1, sp1, sp1, ox + w2 - sp1, oy + h2 - sp1); bitmap.blt(skin, p + sp1, p, q - (sp1 * 2), sp1, ox + sp1, oy, w2 - (sp1 * 2)) bitmap.blt(skin, p + sp1, p + q - sp1, q - (sp1 * 2), sp1, ox + sp1, oy + h2 - sp1, w2 - (sp1 * 2)) bitmap.blt(skin, p, p + sp1, sp1, q - (sp1 * 2), ox, oy + sp1, sp1, h2 - (sp1 * 2)) bitmap.blt(skin, p + q - sp1, p + sp1, sp1, q - (sp1 * 2), ox + w2 - sp1, oy + sp1, sp1, h2 - (sp1 * 2)) bitmap.blt(skin, p + sp1, p + sp1, q - (sp1 * 2), q - (sp1 * 2), ox + sp1, oy + sp1, w2 - (sp1 * 2), h2 - (sp1 * 2)) } }; -
Add your custom object to the save file contents:
SpoilerCode:var $myObject = null; //custom object in global scope (function() { var old_createGameObjects = DataManager.createGameObjects; DataManager.createGameObjects = function() { old_createGameObjects.call(this); $myObject = new My_Object(); }; var old_makeSaveContents = DataManager.makeSaveContents; DataManager.makeSaveContents = function() { var contents = old_makeSaveContents.call(this); contents.myObject = $myObject; return contents; }; var old_extractSaveContents = DataManager.extractSaveContents; DataManager.extractSaveContents = function(contents){ old_extractSaveContents.call(this, contents); if (contents.myObject) {$myObject = contents.myObject;} }; })(); -
This snippet allow you to: create full snapScreen STAGE or CONTAINER + crypto register and save in a folder for import in rmmv or photoshop
PHP:function snapScreenMap(STAGE,w,h) { // create a snap to import in rmmv sofware or photoshop const renderer = PIXI.autoDetectRenderer(w, h); const renderTexture = PIXI.RenderTexture.create(w, h); renderer.render(STAGE, renderTexture); const canvas = renderer.extract.canvas(renderTexture); const urlData = canvas.toDataURL(); const base64Data = urlData.replace(/^data:image\/png;base64,/, ""); const _fs = require('fs'); const crypto = window.crypto.getRandomValues(new Uint32Array(1)); _fs.writeFile(`testSnapStage_${crypto}.png`, base64Data, 'base64', function(error){ if (error !== undefined && error !== null) { console.error('An error occured while saving the screenshot', error); } }); }; -
Xilefian's snippet (reddit) allows you to: get rid of the font outline
Spoilervar _Window_Base_ResetFontSettings = Window_Base.prototype.resetFontSettings;
Window_Base.prototype.resetFontSettings = function() {
_Window_Base_ResetFontSettings.call( this );
this.contents.outlineWidth = 0;
};