Home Technical Talk

The Programming/Scripting MASTER THREAD

2

Replies

  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    SpeCter wrote: »
    You could do a simple A* which is pretty easy to do.
    It's what I am doing now for the ghosts.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    Lamont wrote: »
    It's what I am doing now for the ghosts.
    you got any decent info on that, allways fancied working out how it worked.
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    I think i have my Java A* Code on my computer somewhere if you want fletch, just say a word and i´ll look for it ;)
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    I just got it working a few seconds ago, adding some other things, will post a demo soon.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    SpeCter wrote: »
    I think i have my Java A* Code on my computer somewhere if you want fletch, just say a word and i´ll look for it ;)

    that would be very interesting! thanks.
  • cptSwing
    Options
    Offline / Send Message
    cptSwing polycounter lvl 11
    r_fletch_r wrote: »
    its just a matter of practice. my best advice would be to work as neatly and modularly as possible. break code into functions as much as you can, and print out to the console alot. When you break your scripts down into functions it becomes much easier to locate errors and also becomes alot more readable.
    When you are using variables type the first 3 letters then press CTRL+enter this will give you an auto complete list, if you use that you will misspell things far less :).

    do this tutorial and enable autocomplete for the full mxs api (very very cool)
    http://apps.jhaywood.com/Blog/?c=3dsMax&p=1


    cheers, will give that try!
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    Here is what I have so far, needs optimizations. Going to narrow the search better.

    Click the button to make the path advance, then when goal is reached, it will reset and move the player. There is a bug on the border parts sometimes, it can't find it for some reason.

    http://dl.dropbox.com/u/2851501/PolyCountMan.rar
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    r_fletch_r wrote: »
    that would be very interesting! thanks.

    http://dl.dropbox.com/u/1114083/aStar.zip

    It´s one piece of shit code, but i wrote that 2 years ago :D
    Here is my little java implementation and contains some little bugs but feel free to play around with it.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    thanks!to the Eclipse cave!
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    It could be , that i uploaded an older version(or so it seems -.-)
    Need to take a look at it again!

    Edit:

    Ok that´s the version when i just started with my implementation.
    I´ll update the most recent version when i find it, sorry for the inconvinience:(

    If i can´t find it , i´ll do it again just for you fletch ;)
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    jeez mate, i appreciate the free code, no need to be apologising. take your time :)
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    The code posted will work if the program doesn´t try to check for tiles which are outside of the map(non-existant).
    And this version just gives the shortest path in coords.
    The one i´m looking for right now had a little gui where you could define your map, start/end points, add water and stuff(different ground with different costs).
    Most probably i´ll have to do that again, it´s a nice practice and now the code will most likely be better :D
  • The Flying Monk
    Options
    Offline / Send Message
    The Flying Monk polycounter lvl 18
    r_fletch_r wrote: »
    When you are using variables type the first 3 letters then press CTRL+enter this will give you an auto complete list, if you use that you will misspell things far less :).

    do this tutorial and enable autocomplete for the full mxs api (very very cool)
    http://apps.jhaywood.com/Blog/?c=3dsMax&p=1

    Neat, I didn't realise that the MaxScript editor had this.
    For the guys who use Max Script, are there any other settings like this that you would recommend to make things easier?
  • DEElekgolo
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    Started to program it again, GUI is mostly working now onto the fun part!
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    Ok here it is , just for you fletch(everyone else interested can have it too of course)

    It has some little flaws, but it should find one of the shortest ways.
    The size for the maze is hardcoded atm(sorry!) if you want to make it smaller or bigger you have to change xSize and ySize inside of GameWindow.java.

    You can choose what to paint on the maze with the little icons in the blue square.
    The last square indicates which type of ground is currently selected.
    The little flags are start and finish.

    Feel free to do whatever you want with it and keep in mind, it´s a very simple implementation of the A* algorithm ;).

    A picture of it:
    astar.png

    And here is the project file:
    http://dl.dropbox.com/u/1114083/Pathfinding.zip

    The images folder has to be in the application folder, otherwise all tiles will be white!
    If you run the program it will print the right path to the console.

    It´s a netbeans project file, but you should have no problems getting it to run in another ide.

    The most important part is the Pathfinder class, this is where the magic happens, so please be gentle before argueing about documentation.

    If you got questions, feel free to ask.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    awesome! your a gent
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    Here we are. Getting closer. Now that it works, time to do game rules and ghost personalities. Have a lot of work going on, but still daydream about this. When it's done it will be released code-wise with lots of comments.

    When all is done, let's do some art :)

    Link to the latest PC build.
    http://dl.dropbox.com/u/2851501/PolyCountMan.rar
  • Lamont
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    Here is a solution to a common problem with touch on iOS. Say you are trying to ALWAYS have your left stick as aim and the other as movement. Well you could go by touch ID, but the ID changes. This makes a zone that you can use to be your invisible button that's not a button. You very well could make a touch state for this.

    Possible uses outside of buttons are:
    • Draw this on screen using the objects bounds to get a box touch area.
    • Gesture recognition.

    So what the code does is take the zone height and width values and draws a rectangle where you tell it. Then that function at the end checks to see if THAT instance of the rectangle has a touch inside it, if it does, it registers, else, it won't (if you set it up that way).

    JavaScript (Unity)
    var myZoneWidth : int = 200;
    var myZoneHeight : int = 200;
    private var customBounds : Rect;
    
    myBounds(touch.position, customBounds);
    
    function InsideBounds (touchPosition : Vector2, myBounds : Rect)
    {
           return (myBounds.Contains (touchPosition));
    }
    

    C#
    int myZoneWidth = 200;
    int myZoneHeight = 200;
    Rect customBounds;
    
    myBounds(touch.position, customBounds);
    
    void InsideBounds (Vector2 touchPosition, Rect myBounds)
    {
           return (myBounds.Contains (touchPosition));
    }
    
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    Something for the Unity/.NET peeps. I was looking at some delegates/events stuff with generics, and came across this great article on CodeProject!
    http://www.codeproject.com/KB/cs/event_fundamentals.aspx

    Definitely worth the read, as events are pretty freaking important in a component driven environment such as Unity imho.
  • mLichy
    Options
    Offline / Send Message
    Awesome awesome stuff, thanks for sharing this :D The Slimdx stuff is very cool.
  • haiddasalami
    Options
    Offline / Send Message
    haiddasalami polycounter lvl 14
    Article on matrices by MacaroniKazoo. Also does a lot of python stuff.

    http://www.macaronikazoo.com/?page_id=413
  • Calabi
    Options
    Offline / Send Message
    Calabi polycounter lvl 12
    I have a really basic question.

    What do you do about unnasigned object variables? I mean like a variable that will only be assigned at run time. But it seems the in C# it has to be assigned before, so do you create an empty object or just assign it to a random object.
  • Surfa
    Options
    Offline / Send Message
    Surfa polycounter lvl 12
    I am not quite sure I get what you mean. You can have a varible with nothing assigned to it in c# just define it as
    int a;
    bool b;
    float c;
    etc..
    Or is this not what you meant.

    Also it would be cool if you could add some hlsl or glsl stuff to the list as this would be useful for people getting into tech art.
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    Calabi wrote: »
    I have a really basic question.

    What do you do about unnasigned object variables? I mean like a variable that will only be assigned at run time. But it seems the in C# it has to be assigned before, so do you create an empty object or just assign it to a random object.

    Depends on the scope where the variables are used, and the compiler used. Generally speaking, uninitialized variables that are used with no value will yield compiler errors but it's pretty possible that VC# auto-assigns default values to uninitialized variables. I know the Mono compiler from Unity does it for variables that are declared in the class scope, but not in method or lower scopes.
    This is because the variables declared in the class scope can be re-assigned at any point in the run time. The compiler doesn't know that, so it assigns a default value to it.
    When declaring variables but not initializing them and then using them in a method scope makes no sense for the compiler. Why declare something, but not initialize it and then try to use it? So it will complain about that. :)

    So doing something like this in Unity/Mono will yield compile errors:
    class myClass
    	{
    		
    		void foo ()
    		{
    			int a;
    			int b;
    			
    			// This yields compiler errors because a and b are not initiliazed.
    			int sum = a + b; 
    			float product = a * b;
    		}
    	}
    

    But this will not
    	class myClass
    	{
    		int a;
    		int b;
    			
    		void foo ()
    		{
    			// this compiles fine, because the values of a and b can be changed/assigned by the time they are used by method foo. The compiler does not know that.
    			int sum = a + b; 
    			float product = a * b;
    		}
    	}
    

    Again, it could be that the VC# compiler is more or less forgiving about this, I wouldn't know as I've never tried it. :)
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    man i hate it when your allowed to do shit like that. Whats the value in it, all it does is introduce bugs.
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    It´s commonly bad programming practice not to initialise variables with some dummy values.Most programming languages will do that for you in debug mode but not in release mode(C/C++ for example).
    Forgetting to do so will lead to very unexpected behaviour when switching from debug to release mode.
    Just saying...
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    r_fletch_r: It makes sense for the compiler to allow you to define variables in the class scope but not in the method scope, because the variables declared in the class scope can be changed at runtime before they are used by anything/anyone. The compiler can not foresee that.
    If they are used before they are assigned then, well.... You know, that's what they call runtime errors. :)

    SpeCter: Agreed! I've learned to generally always init my vars with default values. And this rule of thumb holds for every language out there imho! Even more so for the loosely typed languages like Javascript.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    Maph wrote: »
    r_fletch_r: It makes sense for the compiler to allow you to define variables in the class scope but not in the method scope, because the variables declared in the class scope can be changed at runtime before they are used by anything/anyone. The compiler can not foresee that.
    If they are used before they are assigned then, well.... You know, that's what they call runtime errors. :)

    Those are generally initialised in the constructor though are they not? My experienced in this is Java, if I do this in eclipse it gives out to me.
  • Ben Apuna
    Options
    Offline / Send Message
    Surfa wrote: »
    ... Also it would be cool if you could add some hlsl or glsl stuff to the list as this would be useful for people getting into tech art.

    I've added some links on various shader languages, their IDEs, a few tutorials, and a few random links in the first few posts.

    It's not much more than what a Google search will get you though as I haven't studied the subject much myself yet and haven't accumulated many resource links.

    If anyone has better links for this stuff then post them up and I will add then to the list.
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    r_fletch_r wrote: »
    Those are generally initialised in the constructor though are they not? My experienced in this is Java, if I do this in eclipse it gives out to me.

    I would assume so yes. :) Makes sense they get initialized under the hood when the constructor is called.

    Edit: Question, does anyone know of a good alternative IDE for MonoDevelop on Mac? This monstrosity that gets shipped with Unity is a massive resource hog! I'm not looking for a complete Visual Studio alternative (because nothing to this date beats VS imho), but just something with intellisense and proper code analyzing/error messaging.
  • Calabi
    Options
    Offline / Send Message
    Calabi polycounter lvl 12
    Thanks for the info Maph. I did notice, it depended on where I placed it whether I got the error or not, now I know why.
  • haiddasalami
    Options
    Offline / Send Message
    haiddasalami polycounter lvl 14
    Ben Apuna wrote: »
    I've added some links on various shader languages, their IDEs, a few tutorials, and a few random links in the first few posts.

    It's not much more than what a Google search will get you though as I haven't studied the subject much myself yet and haven't accumulated many resource links.

    If anyone has better links for this stuff then post them up and I will add then to the list.

    Nvidia Shader Library. Good reference and code samples to learn from. They have cg and hlsl versions also.
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    Maph wrote: »
    I would assume so yes. :) Makes sense they get initialized under the hood when the constructor is called.

    Edit: Question, does anyone know of a good alternative IDE for MonoDevelop on Mac? This monstrosity that gets shipped with Unity is a massive resource hog! I'm not looking for a complete Visual Studio alternative (because nothing to this date beats VS imho), but just something with intellisense and proper code analyzing/error messaging.

    You could try eclipse with the emonic plugin havent used the plugin myself but I can vouch for Eclipse. its a great program.
    (Thinking about it i've never checked what resources eclipse uses)
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    r_fletch_r wrote: »
    You could try eclipse with the emonic plugin havent used the plugin myself but I can vouch for Eclipse. its a great program.
    (Thinking about it i've never checked what resources eclipse uses)

    I like Eclipse, it's pretty lightweight, especially compared to Monodevelop. But it kinda handles it's projects in a much different manner then VS/Monodevelop. More like how Aptana does it (or more likely, Aptana copied it from Eclipse). Which is kind of a bummer when working in Unity. :(
    Unless you happen to know a workaround to opening .sln files in eclipse?
  • G3L
    Options
    Offline / Send Message
    G3L polycounter lvl 9
    this is awesome! been waiting for something like this on polycount! so is most of the stuff useful if i just want to learn the basics?

    i probably wouldn't go deep with programming since it's something i'd really have to learn and focus on, all the while i still have lots of catching up to do on the art side of things >_<

    thanks once again everyone for contributing! i hope to one day be able to contribute myself :D
  • xXm0RpH3usXx
    Options
    Offline / Send Message
    xXm0RpH3usXx polycounter lvl 13
    r_fletch_r wrote: »
    You could try eclipse with the emonic plugin havent used the plugin myself but I can vouch for Eclipse. its a great program.
    (Thinking about it i've never checked what resources eclipse uses)

    may i humbly ask why you favour eclipse?

    did a little course a few month back using eclipse.
    i "used" (more like i tried too XD) netbeans at home before to get a feel for java and found it muhc more convenient.

    error codes are way better, the interface a little more intuitive and such...
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    I consider Netbeans&Eclipse equal, the only thing i like more about netbeans is that it feels faster(could just be me) and that it has a profiler build in.
    Aside from that they feel just the same to me(didn´t use eclipse for months but i doubt that much has changed since then)
  • Elyaradine
    Options
    Offline / Send Message
    Elyaradine polycounter lvl 11
    I'd pick Eclipse just because I can switch freely between Java and Python.

    Now, if there were a way to debug Unity with Visual Studio... (apparently that's on their to-do list)
  • r_fletch_r
    Options
    Offline / Send Message
    r_fletch_r polycounter lvl 9
    may i humbly ask why you favour eclipse?

    did a little course a few month back using eclipse.
    i "used" (more like i tried too XD) netbeans at home before to get a feel for java and found it muhc more convenient.

    error codes are way better, the interface a little more intuitive and such...

    The Android SDK is integrated with Eclipse. and there are a load of fantastic plugins.
  • xXm0RpH3usXx
    Options
    Offline / Send Message
    xXm0RpH3usXx polycounter lvl 13
    Swing is implemented in Netbeans directly^^

    (i'm sry, i'm not really qualified to say anything intelligent)

    thx for clarifying. so there is the same discussion as with max/maya
  • SpeCter
    Options
    Offline / Send Message
    SpeCter polycounter lvl 14
    Nah not really, they are both great, i switch from time to time.
    And swing is integrated in eclipse too, you only don´t have a gui builder as far as i know :P

    Both are good IDE´s it´s just a matter of what you like more. It´s not like with VS against other IDE´s where you can say it beats the crap out of the other ones.
  • CrazyButcher
    Options
    Offline / Send Message
    CrazyButcher polycounter lvl 18
    originated from a message conversation:
    Ben Apuna wrote:
    Especially Lua which seems more and more awesome the more I read about it. Do you know if Lua is used widely in the industry on the tech art or tools programming side of things?

    My impression is that Lua is used mostly to add scripting features to engines, perhaps so that game designers can make easy edits to data without having to deal with C++.

    yes it's popular with game scripting (realtime system integration), I use it a lot for all kinds of tasks (many people would use python for that, which I never got into).

    Scripting languages like Lua are useful to "generate code", I've used Lua to generate maxscript code or shader code or other things. It can be used for a bit more complex "batch" tasks, parsing directories/files...

    I rip out more and more from luxinia's original codebase into a leaner and looser framework for rendering experimentation https://github.com/CrazyButcher/luxinia2

    Luajit2 is very very cool, it allows calling native code without bindings (C-api dlls) and manage raw-data structures. It can be extremely fast (and Lua is already the fastest interpreted language). People have shown that luajit for certain problems can beat a C implementation due to the nature of JIT being able to optimize depending on the data used.

    python is more wide-spread, but next to its speed Lua is easier to integrate into c/c++ projects. Also its license is very liberal (MIT).

    there is several lua plugins, for example luainterface provides a .net bridge, and there is also luapython to make python callable inside lua and vice versa. Although personally used lua with wxwidgets (Estrela is written in wxlua), that said .net ui is also cool to have.

    all of luxinia's (non engine) code was done in lua (the games, the editor for the games, tools). Especially making editors/tools worked really well (if you have a good UI binding, luxinias ui is also written in Lua) friend and myself yet have to port the luxinia1 ui to luxinia2 sometime hehe

    On the negative side, what comes to my mind compared to something like C# the lack of fixed types for variables of course means less convenience capabilities in IDEs. Debugging also requires some custom work, and the fact that variables are "global" by default is a bit sucky. No built-in unicode support... nevertheless it's a neat tiny language that is quite fast. And the ability to generate code/functions depending on data is lovely.

    Despite python being "larger", one will find a lot of lua's plugin extensions in the "lua for windows" package prebuilt and ready to use and a healthy mailing list at lua-users.org

    mini lua primer for the not so obvious stuff
    -------------------------
    -- tables are general container can be indexed by anything (numbers, 
    -- tables, strings, functions...)
    
    local function blah() end
    tab[blah] = blubb
    tab.name  = blubb -- is same as
    tab["name"] = blubb
    
    
    -- tables are always passed as "pointers/references" never copied
    -- array index starts with 1 !!
    -- they become garbage collected when not referenced anymore
    
    pos = {1,2,3}
    a = { pos = pos }
    pos[3] = 4
    pos = {1,1,1} -- overwrites local variable pos
    a.pos[3] -- is still 4
    
    
    -------------------------
    --[[ multiline 
    comment ]]
    
    blah = [==[ multiline string and comment 
    can use multiple = for bracketing]==]
    
    -------------------------
    --- multiple return values allow easy swapping
    a,b = b,a
    
    -------------------------
    -- object oriented stuff
    -- : operate passes first arg
    a.func(a,blah) -- is same as 
    a:func(blah)
    
    -- metatables allow to index class tables
    myclass = {}
    myclassmeta = {__index = myclass}
    function myclass:func() 
      self --automatic variable through : definiton for the first 
           --arg passed to func
    end
    
    
    object = {}
    setmetatable(object,myclassmeta)
    object:func() -- is now same as
    myclass.func(object)
    
    -------------------------
    --- upvalues for function specialization
    
    function func(obj)
      return function()
        return obj * 2
      end
    
    end
    
    a = func(1)
    b = func(2)
    
    a() -- returns 2
    b() -- returns 4
    
    --- non passed function arguments become nil automatically
    function func (a,b)
      return a,b
    end
    a,b = func(1) -- b is "nil"
    
    --- variable args
    function func(...)
      local a,b = ...
      --- a,b would be first two args
      --- you can also put args in a table
      local t = {...}
    end
    
    
    -------------------------
    --- conditional assignment chaining
    --- 0 is not "false", only "false" or "nil" are
    
    a = 0
    b = a or 1 -- b is 0, if a was false/nil it would be 1
    
    c = (a == 0) and b or 2 -- c is 0 (b's value)
    
    -- the first time a value is "valid" (non-false/nil) that value is taken
    -- that way you can do default values
    
    function func(a,b)
      a = a or 1
      b = b or 1
      
    end
    
    
    
  • Maph
    Options
    Offline / Send Message
    Maph polycounter lvl 8
    Lua is cool! From the limited times I've used it, it kinda reminded me of a combo of Javascript and Pascal, although I hate the latter, I love the former. :)

    Anyone used Love2d yet btw? It's a neat little 2D engine using Lua as it's scripting engine!
    http://love2d.org/
  • cptSwing
    Options
    Offline / Send Message
    cptSwing polycounter lvl 11
    In your collective opinion, would it make sense to dive into C# directly, or to take a detour through Python-ville? I've done a teeny tiny bit of Python in school, have a very, very basic grasp on Javascript and (as seen somewhere above) Maxscript..

    Then again i guess it depends on what i'd like to do with it in the end. Generally i think i'd like to be proficient with writing maxscripts and other pipeline tools to fit my workflow, possibly muck around in Unity (etc.) a little. Not aiming to code in ASM.

    C# came to mind since it seems to be fairy versatile and "easy" to pickup? Any good book recommendations?
  • Calabi
    Options
    Offline / Send Message
    Calabi polycounter lvl 12
    This one seems to be pretty good. The yellow book.

    http://www.csharpcourse.com/
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    cptSwing wrote: »
    In your collective opinion, would it make sense to dive into C# directly, or to take a detour through Python-ville?

    ...<SNIP>...

    C# came to mind since it seems to be fairy versatile and "easy" to pickup? Any good book recommendations?
    I think just getting into ANY language is a good start just to get your mind in that "mode". I find tons of resources on-line and reading theories of things helps as well. Just to read someone's thought process on a given subject can do wonders.
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    Here is a bit of code in C# for a quasi Active Reload in Unity3D. Put this on an object in the scene and run.

    Can be used for anything that requires timing, use your imagination ;). More code for stuff on the way.
    using UnityEngine;
    using System.Collections;
    
    
    //There are many ways to skin a cat, this is my way. Hopefully it will
    //get someone on a different track and come up with something better.
    //If you do, please share :).
    
    public class ActiveReload : MonoBehaviour {
    	
    	//The three rects used for the timer
    	public Rect targetRect;
    	public Rect ReloadRect;
    	public Rect TimeRect;
    	public float reloadSpeed;
    	public float relMove;
    	public int reloadState;
    	private float startTime;
    	private int allTime;
    	private int misses;
    	private int hits;
    	public float targetPos = 0.0F;
    
    	// Use this for initialization
    	void Awake () 
    	{
    		//Setting my ints for Awake
    		allTime = 0;
    		misses = 0;
    		hits = 0;
    		reloadSpeed = 5.0f;
    		reloadState = 3;
    		relMove = 20;
    		//Created rects using the Rect function below.
    		targetRect = MyRect(200, Screen.height/2, 400, 70);
    		TimeRect = MyRect(20, Screen.height/2, Screen.width-50, 70);
    	}
    	
    	void Start()
    	{
    		//Reset timer will keep the time from when the function started vs the time of the game
    		ResetTimer();
    		//This is a FSM it will play and not use much resources. It's waiting for the int reloadState to change
    		StartCoroutine(ReloadState());
    	}
    	//All the update is doing is waiting for a keypress. It would be bad to put the functions for the FSM here.
    	void Update()
    	{
    		if(Input.GetKeyDown("space"))
    		{
    			if(InRect(ReloadRect,targetRect))
    				{
    				reloadState = 2;
    				}
    			else if(!InRect(ReloadRect,targetRect))
    				{
    				reloadState = 1;
    				}
         	}
    		if(Input.GetKeyDown("r"))
    		{
    				reloadState = 0;
         	}
    		
    	}
    //Resets the timer	
    void ResetTimer()
    	{
    		startTime = Time.time;
    	}
    	
    //FSM to control states. There are only 4 states to use. You will see that each state refers to a function.
    public IEnumerator ReloadState()
    {
      while(true)
      {
    	switch(reloadState)
    	{
        	case (0):StartReload();
    			break;
    	    case (1):MissReload();
    			break;
    		case (2):Reload();
    			break;
    		case (3):WaitForReload();
    			break;
    	}
    
        yield return null;
      }
    }
    
    //States for the FSM	
    void StartReload()
    	{
    		relMove = 20*(GenericTimer(1.00f)*reloadSpeed);
    		ReloadRect = MyRect(relMove, Screen.height/2, 10, 70);
    		if(relMove>1176)
    		{
    			reloadState = 1;
    		}
    	}
    void MissReload()
    	{
    		ReloadRect = MyRect(20, Screen.height/2, 10, 70);
    		//Debug.Log("Missed...");
    		reloadSpeed= 5.0f;
    		targetRect.width = 400;
    		targetRect.x=600;
    		hits = 0;
    		misses+=1;
    		reloadState = 3;
    	}
    void Reload()
    	{
    		reloadSpeed+=5;
    		targetRect.x+=5;
    		if(targetRect.width>=20)
    		{
    		targetRect.width-=10;	
    		}
    		hits+=1;
    		if(hits>=allTime)
    		{
    			allTime+=1;
    		}
    		Debug.Log("Perfect Reload!! " + reloadSpeed);
    		reloadState = 3;
    	}
    void WaitForReload()
    	{
    		ResetTimer();
    		ReloadRect = MyRect(20, Screen.height/2, 10, 70);
    	}
    
    //Generic Timer
    public float GenericTimer(float myTime)
    	{
    	float TimeLeft = Time.time - startTime;
        if (reloadState!=0)
        {
            startTime = Time.time;
            TimeLeft = 0;
        }
    	return TimeLeft;
    	}
    
    //GUI Stuff
    void OnGUI()
    	{
    		if (GUI.Button(new Rect(400, 20, 70, 30), "Reload"))
    		{
    			reloadState = 0;
    		}
    		if (GUI.Button(new Rect(400, 70, 70, 30), "Pop"))
    		{
    			if(InRect(ReloadRect,targetRect))
    			{
    				reloadState = 2;
    			}
    			else if(!InRect(ReloadRect,targetRect))
    			{
    				reloadState = 1;
    			}
    		}
    	GUI.Box(new Rect(400, 170, 200, 30),"Hits: " +hits+ " || All-Time "+allTime+" || Misses "+misses);
    	//This slider will move the target box
    	targetRect.x = GUI.HorizontalSlider(new Rect(400, 120, 100, 30), targetRect.x, 200.0F, 500.0F);
    	//These GUI Boxes use the MyRect function
    	GUI.Box(TimeRect, " ");
    	GUI.Box(targetRect, " ");
    	GUI.Box(ReloadRect, " ");
    	GUI.Box(new Rect(300, 500, 400, 90),"How to Play: \r\n Press R key to start the reload \r\n Hit spacebar when the slider is in the hit zone.\r\n Try to rack up a streak:) \r\n 2011 Lamont Gilkey");
    	}
    //Return functions are very powerful. Learn to use them.
    //This creates rects that can be passed around and used
    public Rect MyRect(float xpos, float ypos, float wsize, float hsize)
    	{
    	Rect NewRect = new Rect(xpos, ypos,wsize, hsize);	
    	return NewRect;	
    	}
    
    //This checks to see if the pos rect is within bounds rect and returns true or false
    public bool InRect(Rect pos, Rect bounds)
    	{
    		Vector2 lockon = new Vector2(pos.x, pos.y);
    		//Debug.Log(lockon);
    		return(bounds.Contains(lockon));
    	}
    }
    
  • Lamont
    Options
    Offline / Send Message
    Lamont polycounter lvl 15
    Wanted to tile out an image in PS using save for web but max image size is 8100px or so. This script will cut the image up into how ever many tiles you want on the x and y. Feel free to modify this and make it presentable. I just need it for terrain database work. Uses flattened image. As always save your work before doing crazy scripting stuff.
    //you NEED this, drove me crazy why my pixel values were fubar. you have to tell the script that you are using pixels/inches/cms to do stuff...
    var defaultRulerUnits = preferences.rulerUnits;
    preferences.rulerUnits = Units.PIXELS;
    	
    	if(app.documents.length > 0){ 
    	//Some boxes to collect data for slicing
            var xColumns = parseInt( prompt("X Colums?", 2) );
    		var yColumns = parseInt( prompt("Y Colums?", 2) );
    		var newDocPrefix = prompt("Prefix for tiles?", "FileName");
    		//Gotta write the full path
    		var newDocLoc= prompt("Save location?", "Path");
    		//PS keeps track of the current active document
            var doc = app.activeDocument; 
    		//dimentions of the doc using units defined above
            var docWidth = doc.width;
    		var docHeight = doc.height;
    		//simple math
    		var tileWidth = docWidth / xColumns;
    		var tileHeight = docHeight / yColumns;
    		// selection lasso coords starting upper left and going counter/anti clockwise
    		var x0 = 0;
    		var y0 = 0;
    		var x1 = 0;
    		var y1 = tileHeight;
    		var x2 = tileWidth;
    		var y2 = tileHeight;
    		var y3 = 0;
    		var x3 = tileWidth;
    		var all = 0;
    
    //This goes from left to right top to bottom if you want to go from top to bottom left to right swap the x to the y so you sort the x first
    for(yl = 0; yl < yColumns; yl++){
    	for(xl = 0; xl < xColumns; xl++){
    	selectedRegion = [[x0+(xl * tileWidth),y0+(yl * tileHeight)],[x1+(xl * tileWidth),y1+(yl * tileHeight)],[x2+(xl * tileWidth),y2+(yl * tileHeight)],[x3+(xl * tileWidth),y3+(yl * tileHeight)]];	
    	doc.selection.select(selectedRegion);
    	doc.selection.copy();
    	var targetDoc = documents.add(tileWidth, tileHeight, doc.resolution, newDocPrefix+"_"+(xl+yl));
    	targetDoc.paste();
    	targetDoc = null;
    	var saveTarget = activeDocument;
    	saveTarget.flatten();
    	PSDSaveOptions = new PhotoshopSaveOptions(); 
    	saveFile = new File(newDocLoc+newDocPrefix+"_"+addZeros(all) );
    	saveTarget.saveAs(saveFile,PSDSaveOptions,true,Extension.LOWERCASE);
    	saveTarget.close(SaveOptions.DONOTSAVECHANGES);
    	doc.selection.deselect();
    all++;
    	}
    	}
        }
    //This takes the number and pads it with leading zeros
    function addZeros(number){
       if(number<10){
          number = "000"+number;   
       }else if(number<100){
          number = "00"+number;
       }else if(number<1000){
          number = "0"+number;
       }
       return number;
    }
    
2
Sign In or Register to comment.