Announcement

Collapse
No announcement yet.

UnrealScript Code Samples For Many Things

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    UnrealScript Code Samples For Many Things

    UnrealScript Code Samples For the Community

    Dear Everyone,

    I would like to make this a thread where we can gather code samples to share with the community!

    So if you have a great code sample please share it here!

    ========
    Suggestions
    ========
    Please include as much of the code as possible to make it copy-paste-able for those who are just learning and need to able to see the code in action. (reduce dependencies on other aspects of your code as much aspossible)

    ====
    Rules
    ====

    1. Stay on topic please, this is a thread for POSTING your code samples and explaining them, that is the primary purpose!

    2. Requests for specific codes samples are welcome

    3. Asking broad questions that cannot be answered with code snippets or whole classes being posted as code are not truly on topic.

    ======
    Have fun!
    ======

    Fun and happiness are key!

    ~~~~~

    Code Snippet 1

    How to Make a KActor (like a ball) physically move RELATIVE to the player camera.

    This code enables you to set up a WASD format for use with a non-pawn such as a KActor.

    By contrast, if you don't move the KActor relative to the current viewing angle of the player, then the ball/KActor will not always respond the way you'd think to the WASD directional keys.


    You can also use this code snippet to make a pawn rotate relative to the current camera in 3rd person, though default WASD handles this for you.


    Basic Terminology

    KActor - a class of objects in UDK that run with the Physics Engine, and thus make great alternatives to using pawns/normal player characters. A ball is a common choice, especially for prototyping a game engine.

    Vector - a point in 3D space with this structure

    vector.x
    vector.y
    vector.z

    you can set these properties directly, as vector is really just a struct.

    ~~

    the angles used in Unreal

    Rotator.pitch (z axis angle)
    Rotator.yaw (x/y plane)
    Rotator.roll (not that useful, rotates in the other axis,like if you tilt your head to the side)

    ~~~

    Rotators and Vectors

    Both Rotators and Vectors are structs, not classes, so they are quite easily to manipulate with basic math operations.

    you CAN do vector + vector or other basic operations, like vector * vector;

    Same is true for Rotators.

    ~~~

    Steps to Understanding the Code Sample

    Step 1: When moving a KActor you can use the function KActor.addImpulse(vector) to push the KActor in a certain direction.

    Step 2: To determine the direction we should push the KActor, we need to know the current viewing angle of the player camera, and then we need to set up a vector that is arranged relative to the camera angle

    The player camera angle is stored by the PlayerController class, so

    PlayerController.Rotation = the current viewing angle of the player's camera.


    You can get the PlayerController in a number of ways depending on your current project, google about playercontroller class for more info.

    Step 3: A vector is just a point in 3D space with directional information, to have the KActor actually be pushed at all, we have to add a MAGNITUDE to the vector so that the KActor actually responds sufficiently in the direction the vector is pointing.


    You could stick this code inside the PlayerController class itself, or put it somewhere where you can easily retrieve the PlayerController.

    Code Snippet

    Code:
    //Global vars
    KactorSpawnable ball; //probably you'd have your own class for this
    float magnitude; //serves as the ball's speed 
    
    function moveBackward(){ //relative to current camera facing angle
    
    local rotator camRotation;
    local vector v;
    
    //use Self if inside PlayerController class, or just Rotation
    camRotation = Self.Rotation; //or pc.Rotation or playerController.Rotation
    
    //the yaw direction is the axis of rotation if you spin in 360 
    //while looking around the world
    
    camRotation.yaw += 180 * DegToUnrRot; 
    
    //DegToUnrRot is predefined, not part of my code, 
    //use it in your code to convert from degrees to unreal units
    //You HAVE to do this if you want to get the expected rotations in game. 
    
    //RadToUnrRot for radians
    
    v = Vector(camRotation); 
    //we are converting the camera rotation into a vector
    //this means we are converting an angle into a 
    //3d point with directional information for Unreal engine to use.
    
    
    //this part is very important, 
    //we have to apply a MAGNITUDE of the force, 
    //otherwise its just a a point with directional information, 
    //but no actual distance is being covered.
    
    v.x *= magnitude;  
    v.y *= magnitude;
    v.z = 0;  
    
    //we are ignoring the z-axis information of the 
    //camera rotation because we only want the KActor
    //influenced in the .yaw plane of movement
    //which is the xy plane.
    
    
    //this is the line that actually pushes the KActor.
    
    ball.StaticMeshComponent.AddImpulse(v);
    
    }

    Summary:

    You can convert angles in 3d space, called rotators in Unreal, to vectors, points in 3d space with directional information.

    Code:
    local vector v;
    local rotator r;
    
    v = vect(500,200,50); //you can use vect() instead of v.x = 500 v.y = 200 etc
    r = Rotator(v);
    Note that the vector loses any length information as a rotator is just telling you the direction the vector was point in.

    So all rotators can be converted into unit length vectors.

    Code:
    r.yaw = 90 * degtounrrot;
    v = Vector(r);
    degtounrRot converts from degrees to unreal game units.

    yaw is the rotational plane that you are using if you keep your camera level with the ground and turn around in a circle.

    Then you can apply a MAGNITUDE to the vector to give an actual distance moved in the chosen direction as specified by the vector.

    so vector * magnitude = distance covered in the direction of the vector.

    if vector was a unit vector.

    continuing from the code above:
    This will create a vector whose length is 256 in the direction of the rotator r above
    Code:
    v = v * 256
    //v *= 256 for short
    //v became unit vector from Rotator conversion above
    ~~~

    Why is this useful?

    Say you want to create an Actor (like a barrel or a tree) and move it to exactly 256 units in front of the player camera.

    And you want the actor to face the camera when it is created!

    For this example we are not concerned with the facing of the actor that is spawned.

    Code:
    function spawnActorFacingCamera(){
    local Actor someActor;
    local vector spawnLoc;
    local rotator spawnRot;
    
    //using what we discussed above
    spawnLoc = Vector(PlayerController.Rotation); //viewing angle of player camera
    spawnLoc *= 256;
    //remember v is a unit vector because it is converting a Rotator, the camera angle.
    //so we know the length of vector will be exactly 256;
    
    //Get the angle between the camera and where the actor will spawn
    //so we can make the new actor face the player camera
    spawnRot = Rotator(PlayerController.Location - spawnLoc); 
    
    //you could use your player pawn location instead of the camera
    
    //spawn the actor 256 units in front of player camera, facing the camera when it appears
    someActor = Spawn(class'SomeActorClass',,, spawnLoc,spawnRot);
    }

    So! That's why vector and rotator conversions are so very useful



    Rama

    #2
    Setting Up a Mouse Cursor in UDK Unreal Engine

    Dear Everyone,

    In this tutorial we are

    1. capturing mouse input using only build-in UDK/Unreal script functions
    2. drawing a 2d mouse cursor via HUD class
    3. going from 2D mouse position to 3D world space, using Canvas.DeProject

    4. determining any world geometry/actors/pawns/RTS units that the 2D mouse cursor we made is pointing at AS we move the mouse around the screen



    This code is entirely Self-Sufficient and has no external dependencies.

    you can copy and runs this code after resolving any typos on my part during compile time

    ~~~

    Happy News

    I am very happy to tell you there is an easy built-in way to access the information about changes in the mouse movements by the user!

    I am also happy to say that using just 3 classes and a tiny amount of code I succeeded in getting a 2D mouse cursor in May 2012 version of UDK !



    People have mentioned using ScaleForm to do this.

    I personally find that documentation hard to comprehend and overkill for a simple mouse cursor displayed on screen. Also it seems you need the paid version of Flash Professional to even use Scaleform, it does not seem to be supported in free flash / actionscript IDEs.

    I am very happy to say there is a simple way to gather the mouse movements of the player in-game WITHOUT even using DefaultInput.ini at all.

    Yes indeed.

    Oh was I so happy to discover this!


    Within the PlayerController class there is a way to gather the CHANGE in the x-axis of mouse and the CHANGE in the y-axis over time, as the player moves the mouse.

    So lets say you move mouse quickly to left, there is variable that will say "-3" for example, and then as you slow down the move to the left "-2.1" etc, until you stop moving and it will record 0 again.

    So this information has to be collected by you every moment of time that the game is running, it is constantly changing data, so it must be constantly recorded.

    See below for how to do this!


    ~~~

    Classes You Need To Make

    You should make your own class of the Player Controller, which means you will also need your own Worldinfo class / GameInfo class.

    To make your own classes, create this folder:

    udk/development/src/YOUR_DIR_NAME/Classes

    Then open this file: UDK/UDKCurrentVersion/UDKGame/Config/DefaultEngine.ini

    Then add these lines, other lines included just for reference, they are already there

    Code:
    [Engine.ScriptPackages]
    +NonNativePackages=UTGame
    +NonNativePackages=UTGameContent
    +NonNativePackages=YOUR_DIR_NAME  //add
    Code:
    [UnrealEd.EditorEngine]
    +EditPackages=UTGame
    +EditPackages=UTGameContent
    +EditPackages=YOUR_DIR_NAME   //add
    ~~~

    How To Compile Your Classes and Update DefaultEngine.ini

    To compile your classes and get debug information from the compiler

    in Windows 7 or higher

    UDK/Binaries/win64/

    go to the Binaries directory in windows OS

    then hold the SHIFT key while right clicking on the folder "win64"

    select mouse context option to "open command prompt here"

    this option only shows up if you hold shift while right clicking


    then in the command prompt which is UDK/Binaries/win64/

    type

    udk make


    you have to be in a dos/command prompt to do this.

    you could also make a shortcut on your desktop to run this command.

    but if you want to launch the game to test your code in-game having an actual prompt is better.

    ~~~

    To run your game from command prompt

    this is how you can repeatedly compile your scripts as often as you need to and quickly to test your code and remove any errors using compiler information.

    create a batch file, make a simple textfile and give it the extension .bat

    in this file enter this information only:

    udk C:\UDK\UDK-2012-05\UDKGame\Content\YOURMAP.udk?game=YOUR_DIR_NAME.HappyGameInfo -log


    Note this is only relevant for this code example where the gameinfo class is called HappyGameInfo

    Save the file, then from the prompt, any time you want to test your level with YOUR gameinfo classes, and your map of your choosing, just type the name of your .bat file.

    so if you made a text file called "runHappyMap.bat" then type "runHappyMap" to quickly launch UDK with your map and Classes.

    ~~~

    GameInfo Class


    Code:
    class HappyGameInfo extends GameInfo;
    
    var HappyHUD joyHUD;
    var HappyPlayerController joyfulPlayerController;
    
    defaultproperties
    
    {
    
    	//classes
        PlayerControllerClass	= class'HappyPlayerController'
       // DefaultPawnClass		= class'JoyPawn'
    	HUDType 				= class'HappyHUD'
    	
    	bDelayedStart=false
    	
    }
    
    //Debug Info for you to see your class is being used, press `/~ ingame to see `log info
    
    event PostLogin( PlayerController NewPlayer )
    {
        super.PostLogin(NewPlayer);
        NewPlayer.ClientMessage("Welcome "$NewPlayer.PlayerReplicationInfo.PlayerName);
       	
    	`log("Joy: ================ PostLogin is complete ===============");
    }

    PlayerController Class


    Code:
    class HappyPlayerController extends PlayerController;
    
    
    Simulated Event PostBeginPlay() {
    	
            //essential line
            super.postbeginplay();
    	
    	//set worldinfo var
    	HappyGameInfo(WorldInfo.Game).VictoryController = Self;
    }
    Simulated Event PlayerTick(Float DT){
    	
    	
    	local float mx;  //change in mouse x direction from user
    	local float my;  //change in mouse y direction
    	
    	
    	//capture change in mouse movements
    	//this gives you CHANGE in movement each tick
           //moment of time, as the player moves the mouse.
    
            //playercontroller.playerinput, its built in to unreal engine
            mx = PlayerInput.aMouseX;
    	my = PlayerInput.aMouseY;
    	
    	
    	//ORDER MATTERS SUPER MUST BE AFTER mx and my get set
    
            //if you skip this line below you will break your PlayerController class, 
            //please include it
    
    	super.playertick(DT); 
            //super means "do everything this Event normally does befored I modded it"
           //which is quite a lot since its the PlayerController
    	
    
    
    	//ADJUST MOUSE POSITION
    
            //I am casting worldInfo to our new HappyGameInfo class
            //then accessing the actual Instance of our HUD, joyHUD
            //then setting our own custom variable, MousePosition
    
            //MousePosition is not built into udk HUD class
            
    	HappyGameInfo(WorldInfo.Game).joyHUD.MousePosition.X += mx;
    	HappyGameInfo(WorldInfo.Game).joyHUD.MousePosition.Y += -my;
    
            //In my own code I create variable for the joyHUD in  PostBeginPlay.
            //this shows you how to access GameInfo vars of your own 
            //without using PostBeginPlay
    
           //the PostBeginPlay in HappyHUD is still required however for above code to work
    
    } //end of function
    
    //end of class

    Your HUD Class
    (Heads Up Display / User Interface in game for UDK / Unreal
    )



    Code:
    class HappyHUD extends HUD
            config(Game);
    
    
    //VARS
    var String joyMessage;
    var FONT joyFont;
    
    
    var float joyWidth;
    var float joyHeight;
    
    
    var Vector WorldOrigin;
    var Vector WorldDirection;
    var FontRenderInfo VictoryHudText;
    var Texture2D    CursorTexture;
    
    /** Various colors */
    var const color VictoryCursorColor;
    
    
    var Vector2D    MousePosition;
    
    
    var HappyPlayerController joyfulController
    
    Simulated Event PostBeginPlay() {
    	
            //include this line or you will break your HUD class too hee hee
            super.postbeginplay();
    	
    	//set worldinfo var
    	HappyGameInfo(WorldInfo.Game).joyHUD = Self;
    	
    	//retrieve worldinfo var
    	joyfulController = HappyGameInfo(WorldInfo.Game).joyfulPlayerController;
    	
    	
    	
    }
    
    function centerCursor() {
    	
    	MousePosition.X = joyWidth/2;
    	MousePosition.Y = joyHeight / 2;
    }
    
    
    
    //the variable Canvas is only valid inside DrawHUD() and in postRender() which is not used here
    //this function gets automatically called every frame like .tick() in other classes
    
    function DrawHUD()
    {
    		
         local string StringMessage;
    		
         //projection of ray hit location
    	local vector HitLocation, HitNormal;
    			
    	//get origin and dir
    	Canvas.DeProject(MousePosition, WorldOrigin, WorldDirection);
    		
    	StringMessage = "MouseX" @ MousePosition.X @ "MouseY" @ MousePosition.Y; 
           
    
        //HitLocation may not be valid, use this if to ensure it is valid and not null/None
    	if (joyfulController.Trace(HitLocation, HitNormal, WorldOrigin + (WorldDirection * 100000), WorldOrigin, true) != none) {
    
    
            //HitLocation is the point in 3D space where our 2D mouse cursor is pointing
       joyMessage = "wx" @ HitLocation.x @ "wy" @ HitLocation.y @ "wz" @ HitLocation.z;
    			
    	//set an actor to always follow the cursor as it moves
            //SomeHappyActor.SetLocation(HitLocation);
    			
    	}
    		 
    
        //draw the string to the screen, telling us where cursor is pointing to in 3D world
    	Canvas.DrawColor = VictoryCursorColor;
    	Canvas.SetPos( 10, 10 );
    	Canvas.DrawText( StringMessage, false, , , VictoryHudText );
    
    	//Set position for mouse and plot the 2d texture.
    	Canvas.SetPos(MousePosition.X , MousePosition.Y );
    	Canvas.DrawTile(CursorTexture, 26 , 26, 380, 320, 26, 26);
    		
    	
    	//Sample code for adding messages to your HUD
    	Canvas.SetPos(5,100);
    	Canvas.SetDrawColor(255,0,255,180);
    	
        //yay custom fonts easier to read! set in default properties
    	Canvas.Font = JoyFont;
    	
    	//Update Joy Message
    	Canvas.DrawText(JoyMessage);
    }
    
    
    //PROPERTIES
    defaultproperties
    {
    	//other built in fonts
            //joyFont="UI_Fonts.MultiFonts.MF_HudLarge"	
    	//joyFont = "UI_Fonts.MultiFonts.MF_HudMedium"
    	//joyFont = "UI_Fonts.MultiFonts.MF_HudSmall"
    	
            //sample way to output nice happy info to your HUD in game
            joyFont = "UI_Fonts_Final.HUD.MF_Medium"
    	joyMessage = "Joy!"
    	
    	//change if you want cursor to look different
    	CursorTexture=Texture2D'UI_HUD.HUD.UTCrossHairs'
    
    	VictoryCursorColor = (R = 255, G = 0, B = 255, A = 255)
    	VictoryHudText = (bClipText = true)
    
    				
    }

    Summary

    1. The GameInfo class allows us to connect our custom PlayerController class to our custom HUD class using PostBeginPlay().

    PostBeginPlay is called automatically once the game starts, and this is after all your classes have been instanced into objects in the game world.

    You want to set your variables only AFTER the game starts so they have actual objects in the world attached to them.

    PostBeginPlay lets you do this!

    2. The awesome wonderful yay yay happy feature in PlayerContrller is PlayerInput, which tells us each tick / moment of time how the player is moving the mouse.

    Each tick of time, we are passing the change in the mouse position x/y to the HUD class.

    3. In the HappyHUD class, each moment of time, (DrawHUD and playercontroller.playertick() are called automatically by the Unreal engine), we draw a cursor to the screen, and its position gets modified by the values we pass in from the PlayerController class

    3a. The 2 dimensional x/y coordinates of the mouse cursor are DeProjected into 3D space coordinates so we know where the cursor is in 3D space.

    3b. We draw a trace, a line basically, from the 3D coordinates of the mouse (the 3D position of the cursor is probably quite high above the map if you are looking down from above), to the physical world geometry

    3c. When the trace hits an object, we record where this hit occured, and THIS is the kind of information you would use to reposition an actor/player character / RTS unit.


    Of Great Importance

    You HAVE to draw the trace from the PlayerController class, because remember, the PlayerContrller IS the player camera.

    So where ever the Player camera is, we want to:

    1. use the position of the mouse in 2 dimensional space(Deprojected) and
    2. the PlayerController/Camera position to
    3. draw a line/.trace() down to the physical 3D world space geometry

    note by calling .trace() from the PlayerController class (joyfulController) we get the camera
    position and rotation automatically involved.

    in Trace() we specify start point of trace as WorldOrigin and the destination as far away from
    the WorldOrigin of our cursor in the direction the cursor is point, as determined by DeProject.


    thus the importance of this line:

    Code:
    if (joyfulController.Trace(HitLocation, HitNormal, WorldOrigin + (WorldDirection * 100000), WorldOrigin, true) != none)
    The If statement makes sure we don't take action on HitLocation or HitNormal if they are not valid.

    WorldOrigin and WorldDirection are given to us by:

    Code:
    Canvas.DeProject(MousePosition, WorldOrigin, WorldDirection);

    Some Functions Modify Variables That You Pass In

    Please note in both functions above, some of the variables we pass in, we are actually asking to be given data back, stored in those variables.

    so DeProject is not asking for the WorldOrigin, it is TELLING you the WorldOrigin, but using MousePosition to gather this info.

    PlayerController.trace() is not asking you for the HitLocation and HitNormal, after it runs it is TELLING you this information, stored in whatever variable you pass in.

    ~~~

    From 3D Unit/Position -> MouseCursor / 2D Canvas of HUD



    If you had a point in 3D space that you wanted to map to 2 dimensional space and set the cursor there, such as if you wanted to hover the cursor over an actor/pawn/RTS unit, then use the Canvas.Project() function.



    ~~

    Please Let Me Know


    Please let me know if you find this code useful!

    I am particularly happy about this code because it saved me from the confusion of Scaleform and uses already-built-in functions of UDK, reducing all external dependencies and IDE's to 0.

    Yes 0








    And you can also use the change in mouse x/y info to make your own camera movements, you can map the mouse-x to the yaw of a camera and the mouse y to the pitch.

    So with this code you have

    1. a mouse cursor you can move around on screen

    2. ability to retrieve where a mouse cursor is clicking in 3d world, where it hits 3D geometry/actors

    3. complete access to actual movements of mouse by user for any purpose of your own devising




    Rama

    Comment


      #3
      Dynamic Arrays With Your Custom Classes

      Dear Everyone,

      If you are using code to spawn objects, you more than likely want to keep track of those objects!

      You also are probably wanting to spawn objects that are instances of your own Classes.

      Doing this is syntactically surprisingly complicated

      Here are the basics:

      Simple Dynamic Array

      Code:
      var array<int> intArray;
      Note that you do not use new, or try to make an instance of this var in anyway.

      The .length of the array can be adjusted to 0 to delete entries, then say intArray = None

      But the memory for the array is automatically allocated by the above declaration when you use the array function AddItem.

      ~~~

      .AddItem()


      Code:
      intArray.AddItem(5);
      The additional memory is allocated by Unreal engine for you.


      So

      let me repeat:

      You NEVER need to use the new command with dynamic arrays, in regards to the array itself.

      ~~~

      Making Instances of Your Class Via Code

      To make new instances of a class you can say:

      Code:
      local MyHappyClass happyObj;
      
      happyObj = new class'MyHappyClass';
      You use "local" for all variables when inside a function, "var" for global variables that are part of class itself


      local variables get deleted at the end of the function execution, so a dynamic array you want to repeatedly refer to needs to be GLOBAL and made with "var" not local.

      Locally created variables, made inside a function, persist after the end of the function if stored inside a global dynamic array variable.

      Code:
      class Joy extends Happiness;
      
      //Global Variable
      var array<MyHappyClass> happyArray;
      
      function newHappyObj(){
         local MyHappyClass v;
         local int willGetLost;  //note the name
      
         v = new class'MyHappyClass';
      
         happyArray.AddItem(v);
      
         willGetLost = someVeryImportantValueButAlasNoOneWillKnow;
         return; //end of local context
      }
      After this function runs willGetLost is invalid, but v will live on, referenced by the global array happyArray.

      In this way you can create elements of your global dynamic variable locally, inside a function, but then access them again later in your game's running time via the dynamic array.

      ~~~

      Making Array of Instances of Your Class


      But how to make a DynamicArray of your custom class?


      You might find info as I did on the net saying things like

      Code:
      var array<class<Your class> >; 
      
      //this code is WRONG
      with everyone discussing how you have to space out the two >> so it is not read as an operator.

      But this will make an array of CLASSES of your type of class, not objects that are the instances of your class.

      ~~

      The Actual Correct Code

      to make an array of the actual INSTANCES of your class, you must use this code


      THIS IS THE KEY SYNTAX!


      THE BIG THING which I had to figure out after hours of research


      Code:
      var array <MyHappyClass> happyOBJArray;


      That's it!


      Surprisingly simple.

      ~~~

      Summary:

      Making dynamic arrays and handling their memory allocation is very simple using Unreal Script using the above bits of code.

      Now you can dynamically generate Actors / Objects / Level Geometry and keep track of it easily!


      ~~~

      Dynamic World Making In Game

      I've used dynamic arrays understanding to make a game with UDK where you can build the level yourself inside of the actual game, and save it to file, and load it after closing the Unreal Game Engine and even restarting your computer.

      ~~~

      Enjoooy!





      EverNewJoy



      PS: See http://wiki.beyondunreal.com/Dynamic_array

      for dynamic array functions

      PSS:

      No Internet Replication

      Dynamic Arrays cannot be used for multiplayer games, as dynamic arrays are not replicated to the client

      This is what I've been told by reasonably official documented sources anyways

      Kismet

      Use kismet to handle dynamic objects via the Actor Factory in multiplayer levels.

      I've tested this and it works wonderfully.

      Comment


        #4
        I'll post my code here when my game is at least worth showing.

        Comment


          #5
          i don't understand what is this ,

          Code sample about what? anything you want?

          Comment


            #6
            Make Projectiles Bounce off of Walls and Also Physics Objects Like KActors and Apex

            Dear Everyone,

            Use this code to make a Projectile that will bounce off of

            1.static meshes

            2. AND KActor / physics objects

            3. AND KActors marked as "can become dynamic" (more efficient for engine, but they become static when not activated, so you need code to handle this)

            4. AND Apex destructibles.

            as well as colliding with actual viable pawn targets


            This code also shows you how to set a projectile to have an asymmetric drawscale / size at the time of creation.

            Use this to change the size of your spawned projectiles, including having 1 axis of its size be bigger/smaller than others.


            See my earlier posts for making your own classes and setting up that whole coding/testing environment

            ~~~

            Custom Projectile Class

            This code has no non-standard external dependencies

            You should be able to compile this code easily.

            You will need to spawn your projectile elsewhere in your own code.

            Code:
            class VictoryProj_Plasma extends UTProjectile;
            
            var vector ColorLevel;
            var vector ExplosionColor;
            
            //override so I can show you how
            //to change projectile size
            //at time of creation
            //Init() should be called by you
            //when you spawn the projectile
            function Init(vector Direction) {
            	
            	local vector v;
            	v.x = 2;
            	v.y = 2;
            	v.z = 4;
            	
            	super.Init(Direction);
            	
            	//IT WORKS!!! ASSYMETIC DRAW SCALE!
            	SetDrawScale3D(v);
            }
            
            simulated function ProcessTouch (Actor Other, vector HitLocation, vector HitNormal)
            {
            	if ( Other != Instigator) // && Other != actorToIgnore ) 
            	//who you dont want to take damage
            	{
            		if ( !Other.IsA('Projectile') || Other.bProjTarget )
            		{
            			MomentumTransfer = (UTPawn(Other) != None) ? 0.0 : 1.0;
            			Other.TakeDamage(Damage, InstigatorController, 
                                              HitLocation, 
                                              MomentumTransfer * Normal(Velocity), 
                                              MyDamageType,, self);
            			
            			
            			//comment out if you want projectile to 
                                    //bounce of actors too but still do damage
            			//Explode(HitLocation, HitNormal);
            		}
            	}
            }
            
            simulated event HitWall(vector HitNormal, Actor Wall, PrimitiveComponent WallComp)
            {
            	//projectile code
            	local KActorFromStatic NewKActor;
            	local StaticMeshComponent HitStaticMesh;
            	
            	
            	//use this if statement to have your projectile explode
            	//against certain actors/walls/kactors/whatever
            	
            	//if (Wall == ActorToNotBounceOffOf) {
            		//Explode(Location, HitNormal);
            	//}
            	//else {
            	
            	
            	//Gotta have this line!
            	//This is what makes your projectile
            	//knock Kactors and pawns around
            	MomentumTransfer = 1.0;
            	
            	
            	//actor code taken from actor class
            	//included for your easy reference 
            	//as well as completenesss
            
                    //this code causes KActors that are marked as "can become dynamic"
                    //to ALSO come to life and take damage from your projectile
            	TriggerEventClass(class'SeqEvent_HitWall', Wall);
            	
            	if ( Wall.bWorldGeometry )
            	{
            		HitStaticMesh = StaticMeshComponent(WallComp);
            	if ( (HitStaticMesh != None) && HitStaticMesh.CanBecomeDynamic() )
            	{
            	        NewKActor = class'KActorFromStatic'.Static.MakeDynamic(HitStaticMesh);
            	        if ( NewKActor != None )
            			{
            				Wall = NewKActor;
            			}
            	}
            	}
            	ImpactedActor = Wall;
            	if ( !Wall.bStatic && (DamageRadius == 0) )
            	{
            		Wall.TakeDamage( Damage, InstigatorController, Location, MomentumTransfer * Normal(Velocity), MyDamageType,, self);
            	}
            
            	
            	
            	//YOU HAVE TO COMMENT THIS OUT
            	//otherwise there will be no bounce
            	//just big explosion
            	
            	//set up counter system to see when to explode it
            	//if(counterExpired){
            	
            	
            	//Explode(Location, HitNormal);
            	
            	
            	//}
            	ImpactedActor = None;
            	
            	
            	
            	//===== The Bounce Code =======
            	Velocity = MirrorVectorByNormal (Velocity, HitNormal);
            	Acceleration = AccelRate * Normal(Velocity);
            	SetRotation(Rotator(Velocity));
            	
            	//you HAVE to change the acceleration
            	//or projectile will wander back
            	//to original trajectory eventually
            	//after bouncing
            	
            
            }
            
            simulated function SpawnFlightEffects()
            {
            	Super.SpawnFlightEffects();
            	if (ProjEffects != None)
            	{
            		ProjEffects.SetVectorParameter('LinkProjectileColor', ColorLevel);
            	}
            }
            
            
            simulated function SetExplosionEffectParameters(ParticleSystemComponent ProjExplosion)
            {
            	Super.SetExplosionEffectParameters(ProjExplosion);
            	ProjExplosion.SetVectorParameter('LinkImpactColor', ExplosionColor);
            }
            
            defaultproperties
            {
            	
            	//Use this code to set a mesh
            	//be warned that this is hard on the rendering engine
            	//if you make a lot of projectiles like via shooting for example
            	
            	/* commented out not used
            	Begin Object Class=DynamicLightEnvironmentComponent Name=MyLightEnvironment
                    bEnabled=TRUE
                End Object
                Components.Add(MyLightEnvironment)
            	*/
            	
            	/* commented out not used
                begin object class=StaticMeshComponent Name=BaseMesh
            	
            	    //enter your own mesh name here, use UDK editor right click
            		//to get the actual string name of your mesh
                    StaticMesh = StaticMesh'HappyBallPackage.Meshes.Sphere'
            		Scale=0.2
                   // LightEnvironment=MyLightEnvironment
            		CastShadow=false
            		BlockRigidBody=false
            		BlockZeroExtent=false
            		bUsePrecomputedShadows=false
            		RBCollideWithChannels=(Default=false)
            		bAllowAmbientOcclusion=false
                end object
             
                Components.Add(BaseMesh)
            	*/
            	
            	
            	//Thank you mougli
            	//This makes your projectile have non-point size
            	
            	//custom colision size
            	Begin Object Name=CollisionCylinder
                    CollisionRadius=4
                    CollisionHeight=8  //height is diameter-like, so double radius makes sense
                End Object
            	
            	//you can set a custom particle system here as I've done
            	//use UDK right-click on your particle system and get the string name
            	//enter it below
            	
            	//ProjFlightTemplate=ParticleSystem'VictoryPackage.Effects.victory_projectile1effect'
            	
            	//changed so it will compile for you
            	ProjFlightTemplate=ParticleSystem'WP_LinkGun.Effects.P_FX_LinkGun_MF_Primary'
            	ProjExplosionTemplate=ParticleSystem'WP_LinkGun.Effects.P_WP_Linkgun_Impact'
            	MaxEffectDistance=7000.0
            
            	Speed=1400
            	MaxSpeed=5000
            	AccelRate=3000.0
            
            	Damage=26
            	DamageRadius=0
            	MomentumTransfer=0
            	CheckRadius=26.0
            
            	MyDamageType=class'UTDmgType_LinkPlasma'
            
            	//can make projectiles last longer this way
            	LifeSpan = 3.0
            	
            	//distance beyond which projectile will just be removed from world
            	NetCullDistanceSquared=+144000000.0
            
            	//must be set
            	bCollideWorld = true
            	
            	//change projectile's size
            	DrawScale=1.2
            
            	//I found this sound very annoying 
            	//after 1000 times, commented it out
            	//ExplosionSound=SoundCue'A_Weapon_Link.Cue.A_Weapon_Link_ImpactCue'
            	ColorLevel=(X=1,Y=1.3,Z=1)
            	ExplosionColor=(X=1,Y=1,Z=1);
            }
            ~~~

            Spawning Your Projectile

            Somewheres, maybe in a weapons ProjectileFire();function

            enter this code:

            Code:
            local vector StartLoc;
            local vector FireDir;
            local Projectile SpawnedProjectile;
            
            SpawnedProjectile = Spawn(class'VictoryProj_Plasma',,, StartLoc);
            if( SpawnedProjectile != None && !SpawnedProjectile.bDeleteMe )
            {
            			
            	VictoryProj_Plasma(SpawnedProjectile).Init( FireDir);
            	//casting to your type useful if using custom functions
                    //or vars inside your projectile class
                    //not really necessary here
            }
            ~~~

            To Make Your Custom Projectile Work with Apex Destructibles

            1. Go into UDK

            2. Click on "All Assets"

            3. Enter Filter "apex"


            You might only see one entry

            Find the entry that says its Apex Destructible Damage Parameters

            Its entire name is

            "ApexDestructibleDamageParameters'UDK_APEXDamageMa p.UDKDamageMap'"

            ~~~

            Add a NEW entry

            set the name field as the name of your class, just string character name of your class

            set momentum to something like 2000
            radius 50
            basedamage 100

            basedamage = amount of damage each of your projectiles will do to Apex objects
            radius = radius of damage I believe
            momentum = what makes the pieces of destroyed apex move around when your projectile hits them



            SAVE THE PACKAGE

            right click on the apex damage thing you just modified, and select save




            Now your custom projectile will fully interact with Apex Destructibles!





            Rama

            Comment


              #7
              @Neongho: Nothing special, he just wanted to say to everybody, that he were able to do something - accomplish, but that does not mean that this code is perfect or even good.

              When I see someone asking simple questions yesterday and today writes tutorial - he makes me laugh.
              Just look at this:
              Originally posted by evernewjoy View Post
              Code:
              class Joy extends Happiness;
              
              //Global Variable
              var array<MyHappyClass> happyArray;
              
              function newHappyObj(){
                 local MyHappyClass v;
                 local int willGetLost;  //note the name
              
                 v = new class'MyHappyClass';
              
                 happyArray.AddItem(v);
              
                 willGetLost = someVeryImportantValueButAlasNoOneWillKnow;
                 return; //end of local context
              }
              What do you smoked..?

              @evernewjoy: If you're so good, then write a book...

              Comment


                #8
                aww dont be like that VendorX
                he is trying to do something at least, good effort evernewjoy, even though you appear not to understand a lot of the code you posted, im not 100% sure this thread will take off in the way it was intended.

                Comment


                  #9
                  Has it occurred to some of the above posters that I am taking precious time out of my day to share something I enjoy that I am doing that is actually working so that others might also benefit and succeed in their coding projects?

                  Before you reply consider that I am a human with feelings and emotions, and I am gifting information to the Community and you are sitting here attacking me for it?

                  No wonder its hard to find good info on forums, when this is the sort of response people get for sharing their passions with the world.


                  I do encourage others to post their code samples here, and ignore people who are not very nice.

                  Share your passions with the world anyway.

                  Many nice people ARE reading what you post!



                  Rama

                  Comment


                    #10
                    @ Tegleg,

                    If you think there is code that is incorrect or not explained correctly, feel free to post the correct information here, I am happy to learn too!



                    Rama

                    Comment


                      #11
                      While your attempt is laudable, I am not sure if it's a good idea to put all things in a single thread where it gets cluttered between other posts.

                      Some of your snippets are just copied over from other threads in this forum - why not leave them where they are, so people can find the topic easier by it's thread title and discuss everything in it's own thread?
                      Others are no code snippets but more of tutorials that explain just basic syntax of UnrealScript that should become obvious to anyone who is in the process of learning the language.
                      And others are explained in more depth in other external tutorials or the UDN.

                      If you want to collect code snippets, rather collect links to them in the OP instead of trying to reinvent the wheel. External sites are also often better suited for tutorials than a forum thread. UDKC is a good place to put your tutorials online.

                      Comment


                        #12
                        ok then heres something i see asked again and again, How do start in a vehicle?
                        here is the simplest way i can come up with right now.

                        in your game info there is a function that gets called every time you spawn called RestartPlayer(), so here we will fire off another function to spawn a vehicle and get in it.

                        this goes in you game type class, eg
                        Code:
                        class MyGame extends UTGame;
                        Code:
                        //this function gets called every time you spawn
                        function RestartPlayer(Controller aPlayer)
                        {
                            super.RestartPlayer(aPlayer); 
                        
                             //spawn a vehicle and get in it
                           SpawnVehicle(aPlayer);
                        }
                        
                        //exec means you can press tab and type the name of your function to call it
                        simulated exec function SpawnVehicle(Controller PC)
                        {
                             local vector L;
                          local Rotator R;
                          local Pawn P;
                        local Vehicle V;
                        
                          P = PC.Pawn;
                        
                        //check if there is a pawn associated with the controller
                           if (P != None)
                        	{
                           //get the pawn location and rotation
                              L = P.Location;
                              R = P.Rotation;
                              //get a location above the pawns head
                              L.Z = P.Location.Z + P.GetCollisionHeight();
                        
                          //spawn the vehicle
                           V = Spawn(class'UTVehicle_Scorpion_Content',,,L, R);
                        
                          // get in
                               V.DriverEnter(P);
                        //attach the pawn (like in the manta)
                               V.AttachDriver(P);
                        
                                }
                        }
                        Have Fun

                        Comment


                          #13
                          well things like this and what vendorx kindly pointed out make me think you dont really know whats going on
                          Code:
                          	//I found this sound very annoying 
                          	//after 1000 times, commented it out
                          	//ExplosionSound=SoundCue'A_Weapon_Link.Cue.A_Weapon_Link_ImpactCue'
                          edit:
                          Crusha K. Rool is right, i nearly said a similar thing but posted the code snippet instead

                          Comment


                            #14
                            @tegleg re: commenting out soundcue

                            I commented it out cause it was bothering me, and I was just showing others how to do the same, it was not meant to be a permanent efficient solution, and I included it more as a funny thing, trying to insert some humor.

                            If you think I thought it was a final-product efficient decision well that was not something I ever thought it was.

                            ~~~

                            @tegleg re: your wonderful code example

                            I really like your code example!

                            Thanks for posting!



                            Rama

                            Comment


                              #15
                              Question for Everyone,

                              What is with the strange attitudes?

                              This is all free sharing I am doing in a free community forum.

                              Aren't we all friends who want to see each other succeed in our projects?

                              I am just sharing what I know from experience testing my projects and what I've learned from piecing bits of info together from things other people have learned and posted.

                              I am doing this for a fun as a hobby and am just trying to help others have fun too.

                              I wish more of you would see what I am doing in that context rather than treating me as some sort of imposter.

                              This is my first thread ever,

                              I created my account on this forum just to share my exciting discoveries with everyone and I do not feel very welcomed.

                              Rama

                              Comment

                              Working...
                              X