tModLoader Official tModLoader Help Thread

Maybe someone can send me some custom AI code over and describe what makes each line of code?
This is a very tricky question (I guess it's a question), since AI has so many different elements to it.
Instead of just giving you some AI code and explaining what it all does, should I write something with an explanation on how most vanilla AI is handled (with examples, of course)?
 
Why? I have use that for create my mod(who contains qew boss) and he is not out of date... if you have with Visual studio and use button search of forum, you found all for create correctly a npc. :p
It is kinda out of date, since it's for tAPI.
While most of the actual AI code remains the same, if you are unable to find a function with the same name in the new API, is can be quite the distress.
Also, some variables in vanilla Terraria have been renamed, because of which it can be a pain to find the new and correct ones.
While this tutorial is suited for those that already have some AI or general programming experience, if you're just getting started you need something solid and up-to-date.
 
You have reason, sure. I have already a mod programmed with java in other game and already programmed with many others languages :x (but never C# before.)
 
You have reason, sure. I have already a mod programmed with java in other game and already programmed with many others languages :x (but never C# before.)
Yeah, I see programming experience (may it be with C# or some other language) and/or knowledge as a MUST if you want to mod. Especially with tModLoader as-is, since it's pure C#. I do also, however, want to give the 'dummies' (excuse me for using that term ;) ) among us a chance to get their ideas in game with an API functioning as medium. In this case a more 'back to the basics' example would be best suited. Although the tut blue made is very nice and could help a lot of us, just some general AI knowledge would serve this situation better (IMO). This is in no way me denying or denigrating anything you said, no worries!

This is why at this stage, I advice you, @Marcin JOT.PE, to read up on programming in general if you don't have any programming experience and/or C# if you have experience, but not with C#. We don't want some nasty syntax errors now, do we?
 
Last edited:
Iriazul this will be very helpful if you do this for me
Snrasha this tut is pretty out of date
(I do hope this doesn't turn into a double post. Shame on me).

I've put the whole thing in a spoiler, since I don't feel like taking up one whole forum page (which probably wasn't going to happen anyway).
There's also a (sort of) disclaimer at the bottom. Anyway, hope this helps you! If this isn't enough, I can always try write a bit more.
Oh and do note that this explanation relies on the fact that you know how variables work and how the SetDefaults function in ModNPC works (since you only asked for AI ;) ). Anyway, here you are:

Allright, so to start this off lets talk about the different methods we have to implement AI.
There are three in total: PreAI, AI and PostAI. Now the naming of these methods may speak for themselves, but allow me to elaborate.

PreAI is called before the other two AI methods. PreAI is a function that requires a boolean return type, meaning you HAVE to either return true or false.
Returning true in PreAI will allow vanilla AI to execute and also the AI function of the NPC.
Returning false in PreAI will NOT allow vanilla AI to execute and will also NOT allow the AI function to execute. PostAI, however, is still called.

AI is just a general update function for your NPC.

PostAI is of course called after PreAI and AI (thus also after vanilla AI).

Now the function that I like to use the most is PreAI, since it gives me the most controlled feeling.
To start off in our NPC, lets create the function like I would:

Code:
public override bool PreAI()
{
    return false;
}

Now see here, this is a method which requires a boolean return type (or bool) and we return false.
If you read the above statements correctly, this means that vanilla AI is not executed.

Now this function will get us somewhere, since now we can start to write some AI.
Lets first look at some tools and variables provided by vanilla Terraria and how we can use them.

Every NPC has two VERY handy arrays: ai and localAI. These are both floating number arrays.
If you do not know how an array works, do try to google 'C# arrays explained'.
If you know what an array is and how it functions, take a look at the following:
Code:
public override bool PreAI()
{
    npc.ai[0]++;
   
    if(npc.ai[0] >= 60)
    {
        npc.ai[0] = 0;
    }
   
    return false;
}

Ooh, code! :D
This is a fairly simple piece and an essential bit at that. To break it down: we just made a repeating timer.
To understand this a bit more, lets talk about updates. Terraria is wired so that every second contains 60 updates (hereafter referred to as ticks).
This means that is you want something in terraria to last 1 second, you'll want to rig it so that it remains there for 60 ticks.
120 ticks for 2 seconds, 180 ticks for 3, etc. Now as you can see here, we take the first index in the npc.ai array and add 1 to it every update(++ is the same as += 1).
Then we have an if statement, which checks if the value of that index is 60. Now see here, since we add 1 every update,
it will have reached 60 in one second, thus triggering the code inside the if statement, which will reset the value of npc.ai[0] to 0, thus restarting the timer.
This means we can do something every second. Think firing a projectile, maybe charging at the player, etc.

So now we know that we can use the npc.ai array as a timer... But it can also be used as a state manager!
Check out the following piece of code:
Code:
public override bool PreAI()
{
    if(npc.ai[0] == 0)
    {
        if(npc.life <= npc.lifeMax / 2)
        {
            npc.ai[0] = 1;
        }
    }
    else if(npc.ai[0] == 1)
    {
        npc.ai[1]++;
       
        if(npc.ai[1] >= 60)
        {
            npc.ai[1] = 0;
        }
    }
   
    return false;
}
Allright, so lets break this piece down. First we check if npc.ai[0] is 0, which it always is. All values in both ai and localAI are reset to 0 upon creating a new NPC.
In this case, we have npc.ai[0] functioning as a 'state manager'. To explain that a bit better, lets look at the contents of the first if statement.
In there we check if the NPCs current life is lower than half of the NPCs max life. So we basically check if the NPC has lost half of its life.
If that's true, we set the value of npc.ai[0] to 1. '1' is our new state, because if we look at the 'else if' below the, we check if npc.ai[0] is equal to 1.
Think of this example as some sort of 'rage mode', kinda like the Eye of Cthulu has when he's lost enough life.
At this point our NPC does nothing at first and as soon as it has lost half of its health, it enters its 'rage' and... Still does nothing, really, except for starting the loop we made earlier.
This is an example of how an index in the npc.ai array can function as a state manager.

Now of course, npc.ai can be used for SO MUCH MORE, but it's just too much to go over in one post.
Lets, however, use the above two (essential) AI 'methods' to create something working:
Code:
public override bool PreAI()
{   
    if(npc.life <= npc.lifeMax / 2)
    {
        npc.ai[0] = 1;
    }
   
    int maxSpeed = 3;
    npc.TargetClosest(true);
    Vector2 dir = Main.player[npc.target].Center - npc.Center;
    dir.Normalize();
   
    if(npc.ai[0] == 1)
    {
        npc.ai[1]++;
       
        if(npc.ai[1] >= 60)
        {
            int shootSpeed = 4;
            int damage = 10;
            int knockBack = 0;
            int type = 84;
           
            Projectile.NewProjectile(npc.Center.X, npc.Center.Y, dir.X * shootSpeed, dir.Y * shootSpeed, type, damage, knockBack, Main.myPlayer); 
            npc.ai[1] = 0;
        }
       
        maxSpeed = 5;
    }   
   
    npc.velocity = dir * maxSpeed;
   
    return false;
}
Let me just say this before the last breakdown: This is a VERY simple AI. Nothing compared to some of the AI's in vanilla Terraria.
Allright and lets hop right into it. As you can see, we still have the health check in the code, all the way at the top, since this NPC has a rage mode.
Under there we create an integer called maxSpeed. Then we get the direction vector between the npc and its targeted player.
This is also a very important piece of code, since you can use this to make the NPC move towards a player!
Getting the direction is very simple, it's just the targetPosition - ownPosition.
We then normalize the 'dir' vector so we don't have (possibly) absurdly high values to work with.
Then comes the rage part. If the NPC is raging we start our repeating timer. If that timer reaches 60 after one second we shoot a projectile.
There you can see how you have to spawn a projectile. The parameters we use are:
Code:
Projectile.NewProjectile(xPosition, yPosition, xSpeed, ySpeed, projectileType, projectileDamage, projectileKnockback, owner);
So we spawn the projectile at the NPCs center, give it the correct speeds (xSpeed and ySpeed basically form a direction vector of themselves) and
pass the rest of our variables in. So this bullet we're shooting deals 10 damage, has no knockback, moves... mediocre fast and the type we're shooting is the Pink Laser
used by Gastropods. Then we reset our timer with 'npc.ai[1] = 0;'.
Now that last line inside the 'rage mode code' sets our maxSpeed value to 5. With this we make sure that the NPC moves faster once it rages.
In the last line 'npc.velocity = dir * maxSpeed;' we move our npc towards the player with the given maxSpeed.


I guess that's it for now! I don't normally create tutorials or the likes, so I'm not sure if everything is as well explained as intended,
but I do hope you get some of the basics for AI out of this.
 
Nice now time to start coding my own boss. You will surely ask why I started from such a difficult thing and not knowing #C language. So I started from custom ai and not about things like item, tile of some basic npc because if you can do the hardest thing then all will be easy. And some questions

1. You write everything in Pre Ai. What is the difference between Pre Ai , post Ai en Ai?
2. Can i write for example in Pre ai movement and in Ai Projectiles ?
3. can you explain more over movement , charge , stay above player , jumping ?
4. How about change frames from frame movement to frame charge of stay above player?

Sorry for English all wrote in google tlanslator
 
item.value = Item.sellPrice(0, 10, 0, 0);
Theres something wrong with that line, but I don't know what.
Pls tell me whats wrong with it.
The item is a gun.
I have the same problem with my modded Bow and my modded Rocket Launcher.
 
item.value = Item.sellPrice(0, 10, 0, 0);
Theres something wrong with that line, but I don't know what.
Pls tell me whats wrong with it.
The item is a gun.
I have the same problem with my modded Bow and my modded Rocket Launcher.
Are you getting an error? Not the correct pricing?
Nice now time to start coding my own boss. You will surely ask why I started from such a difficult thing and not knowing #C language. So I started from custom ai and not about things like item, tile of some basic npc because if you can do the hardest thing then all will be easy. And some questions

1. You write everything in Pre Ai. What is the difference between Pre Ai , post Ai en Ai?
2. Can i write for example in Pre ai movement and in Ai Projectiles ?
3. can you explain more over movement , charge , stay above player , jumping ?
4. How about change frames from frame movement to frame charge of stay above player?

Sorry for English all wrote in google tlanslator
Lemme write you a little story, hang on ;)
 
item.value = Item.sellPrice(0, 10, 0, 0);
Theres something wrong with that line, but I don't know what.
Pls tell me whats wrong with it.
The item is a gun.
I have the same problem with my modded Bow and my modded Rocket Launcher.

I'm just guessing, but is the price of the item different than you expected?

The sell price of an item is 20% of the buy price, or the other way around the buy price is 5 times the sell price.

So, that line will make the sell price 10 gold and the buy price 50 gold.

If you want the buy price to be 10 gold, then you should use Item.buyPrice(0, 10, 0, 0).
 
Just to be clear, you are getting that error when building in game, correct? CSteamworks.dll should be in the terraria steam directory, you shouldn't even touch it, and it shouldn't have even come up. Try this: http://javid.ddns.net/tModLoader/generator/ModSkeletonGenerator.html and also if it's not working, show a screenshot of the error screen and your folder and folder path.
[doublepost=1463984297,1463983995][/doublepost]
None of this matters to tmodloader. tmodloader will build the mod itself and doesn't care what you have in your .sln or .csproj file.

UIElements not showing up: The main cause for this is doing something like: recipe.addTile(ItemID.Anvil); instead of the TileID

Other reasons include throwing exceptions in your code somewhere.

Anyway, if you can't see it immediately, move items out of the mod until you see your problem is fixed, or post the troubling code.

error CS1704: An assembly with the same simple name 'Steamworks.NET, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null has already been imported. Try removing one of the references or sign them to enable side-by-side.

error CS1704: An assembly with the same simple name 'MP3Sharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null has already been imported. Try removing one of the references or sign them to enable side-by-side.
this is my error but im not sure if this is the same case as the first one. I used the mod skeleton, and added it to the "C:\Users\Lolz\Documents\My Games\Terraria\ModLoader\Mod Sources" (yes i extracted the skeleton already) but when i build the mod this error shows up. Please help me and thank you in advance :happy:
 
error CS1704: An assembly with the same simple name 'Steamworks.NET, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null has already been imported. Try removing one of the references or sign them to enable side-by-side.

error CS1704: An assembly with the same simple name 'MP3Sharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null has already been imported. Try removing one of the references or sign them to enable side-by-side.
this is my error but im not sure if this is the same case as the first one. I used the mod skeleton, and added it to the "C:\Users\Lolz\Documents\My Games\Terraria\ModLoader\Mod Sources" (yes i extracted the skeleton already) but when i build the mod this error shows up. Please help me and thank you in advance :happy:
Not sure about the first one, unless somehow you have an extra copy of that dll, but the second one is a mp3sharp.dll in the steam terraria directory that you need to delete.
 
Hi guys, can someone teach me how to make an npc sell an item from terraria? for example, an iron ore and for a custom pricing like 1 silver for 1 iron ore.
ive seen the code from exampleperson.cs but it only shows how to sell items from the mod
 
Help please (bad english is coming!)
someone knows a easy way to make enemys ?like use AI vanilla,because a made a mod with 5 set armors,12 swords,8 guns and 7 accessories, but not enemys :( I want to put my mod to download but I want make enemys frist.If any one knows a easy way to make mobs and bosses,please tell me(if possible make a "exemple code" to me,I like made sprites not codes)
anyway thanks to read!
 
Back
Top Bottom