Bedrock Wiki
  • Discord
  • Contribute
  • bedrock.dev
  • MS Learn
Beginner's Guide
  • Guide
    • 1. Introduction
      guide
    • 2. Add-Ons Explained
    • 3. Software & Preparation
    • 4. Project Setup
    • 5. Create a Custom Item
    • 6. Create a Custom Entity
    • 7. Blockbench: Modeling, Texturing & Animating
    • 8. Adding a Loot Table, Spawn Rule & Crafting Recipe
  • Extra
    • a. Understanding JSON
    • b. Download Example Packs
    • c. Troubleshooting
      help
    • d. Advanced Manifest
    • e. Format Versions
    • f. Project Setup Android
Animation Controllers
  • Intro to Animation Controllers
    guide
  • Entity Commands
  • AFK Detector
  • Death Commands
  • Molang into Scoreboard
  • Respawn Commands
Blocks
  • General
    • Intro to Blocks
      guide
    • Block Components
    • Block Tags
    • Block States
    • Block Traits
    • Block Permutations
    • Block Events
      Scripts
    • Block Event Migration
      help
    • Blocks as Items
    • Troubleshooting Blocks
      help
  • Visuals
    • Block Culling
    • Block Models
      guide
    • Block Texture Animation
    • Block Texture Variation
    • Block Tinting
  • Tutorials
    • Applying Effects
      Scripts
    • Avoiding State Limit
    • Block Orientation
    • Fake Blocks
      Scripts
    • Intercardinal Orientation
      Scripts
    • Ore Loot Tables
      Scripts
    • Tool-Based Destruction
  • Vanilla Re-Creations
    • Custom Crops
      Scripts
    • Custom Glass
    • Custom Glazed Terracotta
    • Custom Heads
      Scripts
    • Custom Trapdoors
      Scripts
  • Documentation
    • Block Format History
    • Block Shapes
    • Block Sounds
    • Redstone Components
    • Vanilla Block Models
    • Vanilla Block Tags
    • Vanilla Voxel Shapes
Commands
  • General
    • Intro to Command Blocks
    • Functions
    • Block States
    • Coordinate System
    • Giving NBT Items
    • Scoreboard Operations
    • Understanding Selectors
  • Commands
    • Damage
    • Execute
    • Playanimation
    • Playsound
  • On Event Systems
    • On First World Load
    • On Player First Join
    • On Player Join
    • On Player Leave
    • On Player Death
    • On Player Respawn
  • Scoreboard Systems
    • Entity Counter
    • Scoreboard Timers
    • Comparing And Retrieving Scores
  • Techniques
    • Execute Logic Gates
    • Execute at Block Variant
    • MBE - Max's Block Entity
    • FMBE - A New Way to Create Display Entities
    • Item Drop Detection
    • Look Detection
    • Movement Detections
    • Orbital Camera
  • Useful Creations
    • Compass Display
    • Custom Crafter
    • Multiplayer Position Rearrangement
      function
Concepts
  • contents.json
  • Molang
  • Namespaces
  • Overwriting Assets
  • Shaders
  • Sounds
  • Subpacks
  • Texture Atlases
  • textures_list.json
Documentation
  • Advanced Molang
  • File Types
  • Fog IDs
  • Material Configuration Description
  • Molang Queries
  • Pack Folder Structure
  • Shared Constructs
  • Sound Definitions
  • Vanilla Materials
Entities
  • General
    • Intro to Entities BP
      guide
    • Intro to Entities RP
      guide
    • Troubleshooting Entities
      help
    • Entity Events
    • Entity Properties
    • NPC Dialogue
    • Render Controllers
    • Spawn Rules
  • Tutorials
    • Convert Points Between Any Space (World, Entity, Bones)
    • Creating Boats
    • Detecting Other Entities
    • Disabling Team Damage
    • Dummy Entities
    • Entity Attacks
    • Entity Holds Item
    • Entity Movement
    • Entity Timers
    • Introduction to AOE Clouds
    • Invulnerable Entities
    • Look at Entity
    • Riding Flying Entities
    • Sleeping Entities
    • Solid Entities
    • Spawning Tamed Entities
      Scripts
    • Village Mechanic
  • Documentation
    • Dummy Components
    • Non-Mob Runtime Identifiers
    • Projectiles
    • Runtime Identifiers
    • Vanilla Usage Components
    • Vanilla Usage Spawn Rules
Items
  • General
    • Intro to Items
      guide
    • Item Components
    • Item Tags
    • Item Events
      Scripts
    • Item Event Migration
      help
    • Item Catalog
    • Troubleshooting Items
      help
  • Tutorials
    • Custom Armor
    • Custom Food
      Scripts
    • Custom Pottery Sherds
    • Custom Weapons
    • Equipment-Based Commands
    • Spawning Items
    • Throwable Items
  • Documentation
    • Enchantments
    • Attachables
    • Item Format History
    • Numerical Item IDs
    • Vanilla Item Groups
    • Vanilla Item Tags
    • Vanilla Usage Components
JSON UI
  • General
    • Intro to JSON UI
      guide
    • Best Practices
      guide
  • Tutorials
    • Adding HUD Elements
    • Aseprite Animations
    • Buttons and Toggles
    • Modifying Server Forms
    • Preserve Title Texts
    • String to Number
  • Documentation
    • JSON UI Documentation
Loot, Recipes & Trading
  • General
    • Trading Behavior
  • Documentation
    • Loot Tables
    • Trade Tables
    • Recipes
    • Item Functions
  • Tutorials
    • Randomized Structure Loot
Meta
  • Add-On Performance
  • Style Guide
  • Useful Links
  • Using Schemas
  • Version Control
  • Q&A
    • Blocks and Items Q&A 2024/08/30
    • Deferred Technical Preview Q&A 2024/02/23
    • GameTest Q&A 2021/08/06
    • Scripting and Editor Q&A 2023/09/22
    • World Generation Q&A 2024/11/15
NBT
  • General
    • .mcstructure
  • Tutorials
    • Enabling Experiments by Editing NBT
    • Extending Structure Limits
  • NBT in Depth
    • About NBT (Named Binary Tag)
    • NBT Libraries
    • Reading NBT Example
Particles
  • General
    • Intro to Particles
      guide
  • Tutorials
    • Disabling Particles
  • Documentation
    • Vanilla Particles
Scripting
  • General
    • Intro to Scripting
    • What is Script API?
    • API Modules
  • Tutorials
    • Block Placement Prevention
    • Custom Commands
    • GameTests
    • Script Core Features
    • Script Forms
    • Script Privileges
    • Script Requests API
  • Documentation
    • Engine Environment
    • Script Resources
    • Script Watchdog
    • Troubleshooting JavaScript
    • TypeScript
Servers
  • Software
    • Bedrock Server Software
  • Protocols
    • Bedrock Protocol
    • NetherNet Protocol
    • RakNet Protocol
Text & Localization
  • General
    • Intro to Text & Localization
    • Raw Text
    • Splashes
  • Emojis & Symbols
    • Fonts
    • Intro to Emojis
    • Custom Emojis
    • Input Keys
Visuals
  • General
    • Introduction to Entity Visuals
      guide
    • Bedrock Modeling
    • Custom Death Animations
    • Effects in Animations
    • Material Creations
    • Materials
    • Math-Based Animations
    • Skin Packs
  • Tutorials
    • Entity Texture Animation
    • Glowing Entity Texture
    • Hurt Animations
    • Leash Position
    • Player Geometry
    • Remove Entity Shadows
    • Retexturing Spawn Eggs
  • Ideas
    • Structure Presentation
World Generation
  • General
    • Intro to World Generation
      guide
    • Biomes
      guide
    • Feature Types
    • Jigsaw Structures
  • Tutorials
    • Block Conditions for Features
    • Generating Custom Ores
    • Generating Custom Structures
    • Generating Patches
    • Heightmap Noise
  • Documentation
    • Biome Tags

Custom Crops

Custom Crops
      • custom_crop.json
      • custom_food.json
      • custom_seeds.json
          • custom_crop_mature.json
          • custom_crop_young.json
      • cropGrowth.js
      • index.js
    • contents.json
    • manifest.json
    • pack_icon.png
        • custom_crop.geo.json
      • en_US.lang
      • languages.json
          • custom_crop_0.png
          • custom_crop_1.png
          • custom_crop_2.png
          • custom_crop_3.png
          • custom_food.png
          • custom_seeds.png
      • item_texture.json
      • terrain_texture.json
      • textures_list.json
    • blocks.json
    • contents.json
    • manifest.json
    • pack_icon.png
Download as ZIP Download as MCADDON
BP/scripts/cropGrowth.js
js
import { system, EquipmentSlot, GameMode } from '@minecraft/server';

const cropGrowthComponentName = "wiki:crop_growth";
/** @type {import("@minecraft/server").BlockCustomComponent} */
const BlockCropGrowthComponent = {
    onRandomTick({ block }, { params }) {
        // Growth parameters
        const growthState = params.growth_state;
        const maxGrowth = params.max_growth;
        const minLightLevel = params.min_light_level;
        // Ensure that the minimum light level is met
        if (block.getLightLevel() < minLightLevel)
            return;
        const { permutation } = block;
        // Get the current growth of the crop
        const growth = permutation.getState(growthState) ?? maxGrowth;
        // Ensure that the crop is not already fully grown
        if (growth === maxGrowth)
            return;
        // Only grow on some random ticks
        if (!randomShouldCropGrow(block, params))
            return;
        // Increment the growth state
        block.setPermutation(permutation.withState(growthState, growth + 1));
    },
    onPlayerInteract({ block, dimension, player }, { params }) {
        if (!player)
            return;
        const equippable = player.getComponent("minecraft:equippable");
        if (!equippable)
            return;
        const mainhand = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
        if (!mainhand.hasItem())
            return;
        const hasBoneMeal = mainhand.typeId === "minecraft:bone_meal"; // Whether the player is holding Bone Meal
        const hasRapidFertilizer = mainhand.typeId === "minecraft:rapid_fertilizer"; // Whether the player is holding Super Fertilizer (from Minecraft Eduction)
        // Exit if the player is not holding Bone Meal or Super Fertilizer
        if (!hasBoneMeal && !hasRapidFertilizer)
            return;
        const isCreative = player.getGameMode() === GameMode.Creative; // Whether the player is in creative mode
        // Growth parameters
        const growthState = params.growth_state;
        const growthRange = params.growth_on_fertilize;
        const maxGrowth = params.max_growth;
        const { permutation } = block;
        if (hasRapidFertilizer || isCreative) {
            // Grow the crop fully when the player is holding Super Fertilizer or is in creative mode
            block.setPermutation(permutation.withState(growthState, maxGrowth));
        }
        else {
            // Add a random amount of growth when the player is using Bone Meal and is not in creative mode
            let growth = permutation.getState(growthState);
            growth += randomInt(...growthRange); // Add a random amount of growth in the "growth_on_fertilize" range
            growth = Math.min(growth, maxGrowth); // Prevent the new growth from being over the maximum
            block.setPermutation(permutation.withState(growthState, growth));
        }
        // Decrement the item stack when the player is not in creative mode
        if (!isCreative) {
            if (mainhand.amount > 1)
                mainhand.amount--;
            else
                mainhand.setItem(undefined);
        }
        // Play effects
        const effectLocation = block.center();
        dimension.playSound("item.bone_meal.use", effectLocation);
        dimension.spawnParticle("minecraft:crop_growth_emitter", effectLocation);
    },
};
system.beforeEvents.startup.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent(cropGrowthComponentName, BlockCropGrowthComponent);
});
/**
 * @param {number} min The minimum integer
 * @param {number} max The maximum integer
 * @returns {number} A random integer between the `min` and `max` parameters (inclusive)
 */
function randomInt(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}
function randomShouldCropGrow(crop, growthParams) {
    const growthSpeed = getGrowthSpeed(crop, growthParams);
    const growthChanceRange = Math.floor(25 / growthSpeed);
    return randomInt(0, growthChanceRange) === 0;
}
/**
 * @param {import("@minecraft/server").Block} crop The block to get the growth speed of
 * @returns {number} A number representing the growth speed of the crop
 */
function getGrowthSpeed(crop, growthParams) {
    let speed = 1;
    // Increase growth speed based on nearby farmland blocks and their moisture
    for (const farmland of getFarmlandIterator(crop, growthParams.farmland_search_range)) {
        let speedModifier = growthParams.farmland_speed_modifier;
        const moisture = farmland.permutation.getState("moisturized_amount");
        if (moisture > 0) {
            speedModifier += growthParams.farmland_moisture_speed_modifier;
        }
        const isDirectlyBelowCrop = farmland.x === crop.x && farmland.z === crop.z;
        if (!isDirectlyBelowCrop) {
            speedModifier *= growthParams.neighboring_farmland_speed_multiplier;
        }
        speed += speedModifier;
    }
    // Halves the growth speed if there are surrounding crops of the same type in vanilla (where "crowding_speed_multiplier" is 0.5)
    if (isCrowded(crop)) {
        speed *= growthParams.crowding_speed_multiplier;
    }
    return speed;
}
/**
 * @param {import("@minecraft/server").Block} crop
 * @param {number} searchRange Maximum offset in each direction of the X and Z axes where farmland can be found
 * @returns {Generator} A generator that iterates through each farmland block in an area underneath the crop
 */
function* getFarmlandIterator(crop, searchRange) {
    for (let x = -searchRange; x <= searchRange; x++) {
        for (let z = -searchRange; z <= searchRange; z++) {
            const block = crop.offset({ x, y: -1, z });
            // Yield the block if it is farmland
            const isFarmland = block?.typeId === "minecraft:farmland";
            if (isFarmland)
                yield block;
        }
    }
}
/**
 * @param {Block} crop
 * @returns {boolean} Whether there are surrounding crops of the same type
 */
function isCrowded(crop) {
    const northBlock = crop.north();
    const southBlock = crop.south();
    const westBlock = crop.west();
    const eastBlock = crop.east();
    const isEnclosed = (westBlock?.typeId === crop.typeId || eastBlock?.typeId === crop.typeId) &&
        (northBlock?.typeId === crop.typeId || southBlock?.typeId === crop.typeId);
    if (isEnclosed)
        return true;
    const isCropDiagonallyAdjacent = northBlock?.west()?.typeId === crop.typeId ||
        northBlock?.east()?.typeId === crop.typeId ||
        southBlock?.west()?.typeId === crop.typeId ||
        southBlock?.east()?.typeId === crop.typeId;
    if (isCropDiagonallyAdjacent)
        return true;
    return false;
}

export { cropGrowthComponentName, randomShouldCropGrow };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
Edit cropGrowth.js on GitHub

Code samples on this page are licensed under the MIT License

Bedrock Wiki by Bedrock OSS

"Minecraft" is a trademark of Mojang AB.

Bedrock OSS, Bedrock Wiki and bedrock.dev are not affiliated in any way with Microsoft or Mojang AB.

  • Privacy Policy
  • Join our Discord
  • Learn how to Contribute
  • Visit our Repository