Search Unity

[UNITY 5 FPS Tutorials] GTGD S3 - Advanced First Person Shooter

Discussion in 'Community Learning & Teaching' started by GTGD, Oct 9, 2015.

  1. Deleted User

    Deleted User

    Guest

    Oh wow...I cannot believe I missed that after going through it multiple times!! haha

    Thanks for taking the time to read through and spotting the mistake! Really appreciate it!!

    On to chapter 7!!

    :) Thanks!
     
  2. Parzivell

    Parzivell

    Joined:
    Sep 11, 2013
    Posts:
    3
    Hello,
    I am on ItemPickup [58] and everything was working fine until i was told to move these outside of the If statement.

    public void CallEventObjectThrow()
    {
    if(EventObjectThrow != null)
    {
    EventObjectThrow();
    }
    playerMaster.CallEventHandsEmpty();
    playerMaster.CallEventInventoryChanged();
    }

    public void CallEventObjectPickup()
    {
    if(EventObjectPickup != null)
    {
    EventObjectPickup();
    }
    playerMaster.CallEventInventoryChanged();
    }

    When i do this, i can no longer throw my object, it just lands on the floor in front of me, i can't pick it back up, the inventory doesn't update and i get no errors. I have been looking over my scripts for the past few days and cant seem to find the problem.

    Just to clarify, i have the cube as item in both tag and layer.
    I have the character controller set to player in both tag and layer.
    I have the inputs set up correctly

    Please help, i am going to go insane in a few days :D
     
  3. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    You also need to put SetInitialReferences in the Start method
     
    Parzivell likes this.
  4. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Definite A, nice work and all objectives completed!
    That's a lot of evil boxes to destroy :)
     
    crifab93 likes this.
  5. Parzivell

    Parzivell

    Joined:
    Sep 11, 2013
    Posts:
    3
    I'm sorry but I don't understand what you mean. In the "Item_Master" script, there is no Start method, there is only an OnEnable method which I already have called the "SetInitialReferences" method. There is one in the item throw script but I have already called the "SetInitialReferences" method. If you need any further information, I am more than willing to give it to you. I do feel a bit bad though cos I don't want to be wasting/bothering you.
     
  6. Deleted User

    Deleted User

    Guest

    Hi :) You need to add a start method into your item_master script, just add it underneath the on enable method and add it like this! :)

    Code (CSharp):
    1.  
    2.     void Start()
    3.     {
    4.         SetInitialReferences ();
    5.     }
    I also have it commented out in my OnEnable method, I'm pretty sure he does that at some point in one of his videos, can't remember which one!

    Hope this helps! :)
     
  7. Parzivell

    Parzivell

    Joined:
    Sep 11, 2013
    Posts:
    3
    I find it amazing how GTGD immediately knew what the problem was only with a tiny amount of information...and how I went on to still not understand. Just wanted to thank M10Pearson(as I see you went through what I went through) and GTGD! its not programming if you don't make mistakes :D
     
  8. Deleted User

    Deleted User

    Guest

    True that! My programming teacher recently sat at home for like 8 hours reading through code to find out what the problem was trying all sorts of different methods of programming it all to finally find out that it was literally just one letter that was the problem with capitalisation! haha everybody makes the mistakes and sometimes can't spot it for hours :p
     
  9. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
  10. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    A+, very nice work and it's a bit of a platform game too!
     
  11. yuplis

    yuplis

    Joined:
    Apr 2, 2016
    Posts:
    2


    Thanks to you :) still working on it and im working hard to get a complete game so i can release it to the public

    :) thanks again
     
  12. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    WOW that is awesome!
    Keep at it you've got a really good looking project there. Lol I found it funny how you got taken down by some primitive barbarians :p
     
  13. Deleted User

    Deleted User

    Guest

    Hi!

    I've commented as best I can in my code, on what I understand ect..

    However could you please explain why and how the set initial references method is used ect?

    Thanks

    Mike!
     
  14. marcs77

    marcs77

    Joined:
    Jul 14, 2013
    Posts:
    4
    I was doing the enemy chapter, when I noticed that the enemy chases you even though you aren't in his field of view. So I've decided to implement a proper detection that takes into account his fov and I've added another radius called stealth radius where he can "hear" you if you are behind and very close.

    It works pretty well for me :p
    Code (CSharp):
    1.  
    2.  
    3. //Add this variables at the beginning
    4. public float stealthRadius = 15f;
    5. public float fov = 75f; //in degrees
    6.  
    7. //Put this inside the SetInitialReferences
    8. fov = Mathf.Cos(fov * Mathf.Deg2Rad);
    9.  
    10. //Modify the CanPotentialTargetBeSeen
    11. bool CanPotentialTargetBeSeen(Transform target)
    12. {
    13.     if (Physics.Linecast(head.position, target.position, out hit, sightLayer))
    14.     {
    15.         if(hit.transform == target &&
    16.             (Vector3.Dot(head.forward, (target.position - head.position).normalized) >= fov ||
    17.             Vector3.Distance(head.position, target.position) < stealthRadius))
    18.         {
    19.             enemyMaster.CallOnTargetSet(target);
    20.             return true;
    21.          }
    22.         else
    23.         {
    24.             enemyMaster.CallOnLostTarget();
    25.             return false;
    26.         }
    27.     }
    28.     else
    29.     {
    30.         enemyMaster.CallOnLostTarget();
    31.     }
    32.     return false;
    33. }
    PD:
    Something I've forgot to mention is that the Bip001 Head object is looking down, so the script won't work properly. To fix this you need to create an empty object inside (called Head), rotate it so that the z axis is looking forward, and assign it to the head variable. Also, I would recommend to change the Update to LateUpdate so that the head doesn't flicker.
     
    Last edited: Apr 5, 2016
  15. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    I just made that up so that I can run instructions that I really need to run before any of the other instructions in that script are executed
     
  16. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Very nice mod there :), added to the list of contributed code!
     
    marcs77 likes this.
  17. AtomicSludge

    AtomicSludge

    Joined:
    Apr 9, 2016
    Posts:
    1
    Greetings. I have completed "most" of the items in chapter 1. I did, however, get a bit distracted making some basic models, sound effects, and particle effects.

     
    Saurabh-Saralaya, K_Kaze and marcs77 like this.
  18. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    LOL, that was almost disturbing
    A for turning Chapter 1 into a sci-fi horror scene!
     
  19. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
    Still grinding away at these tutorials. I really like how it's broken up into small & digestible chunks. Really gives me a chance to let the new stuff sink in as well as give me lots of opportunities to get distracted and wander off with silly things. For example, after completing #84 Enemy Collision Field, I decided to play around with destroying the gameObject off screen. What do you think of this?:

    Code (CSharp):
    1.  
    2. // in Enemy_Health.cs
    3. // Added the following variables at the top
    4. public bool despawnOffCamera;    // bool in case I just want the original destroy in 10 to 20 seconds
    5.  public Camera playerCam;           // drop in FirstPersonCharacter camera to check the viewport
    6.  public float giveUpTime = 30.0f;    // time to wait before giving up destroying it anyway to avoid clutter
    7.  
    8.  
    9. // Altered existing function
    10.      void DeductHealth(int healthChange) {
    11.             enemyHealth -= healthChange;
    12.  
    13.             if(enemyHealth <= 0) {
    14.                 enemyHealth = 0;
    15.  
    16.                 // Should this be copied and pasted before each destroy?
    17.                 enemyMaster.CallEventEnemyDie();
    18.                 //  I haven't noticed any issues or got any warnings in Unity so I left it as is.
    19.  
    20.                 if (despawnOffCamera) {
    21.                     // workout how long to wait before giving up then away we go
    22.                     giveUpTime += Time.time;
    23.                     StartCoroutine(CheckIfVisible());
    24.                 } else {
    25.                     Destroy(gameObject, Random.Range(10, 20));
    26.                 }
    27.             }
    28.         }
    29.  
    30.  
    31. // Added these functions
    32.         IEnumerator CheckIfVisible() {
    33.             while (true) {
    34.                 AmIVisible();
    35.                 yield return new WaitForSeconds(2f);
    36.             }
    37.         }
    38.  
    39.         void AmIVisible() {
    40.             if(playerCam != null) {
    41.                 Vector3 testView = playerCam.WorldToViewportPoint(transform.position);
    42.                
    43.                // Any value less than 0, the transform is off screen
    44.                // I wound up using -2 to make sure the majority of the body is gone
    45.                // While testing it, the numbers were confusing and these just seem to work good enough.
    46.                 if(testView.x < -2 || testView.y < -2 || testView.z < -2 || Time.time >= giveUpTime) {
    47.                     StopAllCoroutines();
    48.                     Destroy(gameObject);
    49.                 } else {
    50.                 }
    51.             } else {
    52.                 // Incase I forget to set which camera to use, the gameObject is immediately destroyed
    53.                 // the sudden disappearance of the enemy is a good reminder to do something about it.
    54.                 StopAllCoroutines();
    55.                 Destroy(gameObject);
    56.             }
    57.         }
    58.  
     
  20. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
    I found this handy little code to draw the enemy FOV in the #scene view to help with debugging and tweaking values. I altered the variables to match the existing code in Enemy_Detect.cs (obviously with the FOV edits too) so that it can be copied and pasted in. I also added 1 to the y position because sometimes it got lost in the floor.
    http://answers.unity3d.com/answers/21180/view.html
    Code (CSharp):
    1.  
    2.        float  halfFOV;
    3.  
    4. halfFOV = fov / 2.0f; // Drop this in InitialReferences somewhere before the FOV variable gets converted otherwise you just get a straight line.
    5.  
    6.        void OnDrawGizmosSelected() {
    7.             Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFOV, Vector3.up);
    8.             Quaternion rightRayRotation = Quaternion.AngleAxis(halfFOV, Vector3.up);
    9.             Vector3 leftRayDirection = leftRayRotation * transform.forward;
    10.             Vector3 rightRayDirection = rightRayRotation * transform.forward;
    11.             Gizmos.DrawRay(transform.position + new Vector3(0, 1, 0), leftRayDirection * detectRadius);
    12.             Gizmos.DrawRay(transform.position + new Vector3(0, 1, 0), rightRayDirection * detectRadius);
    13.         }
    14.  
    edit: This function does not need to be called, it is built in to Unity.
     
    Last edited: Apr 10, 2016
  21. Racine-Z

    Racine-Z

    Joined:
    Dec 10, 2015
    Posts:
    4
    Hello , I wanted to ask you something about your script sistem , I understand the system of separate scripts, but wanted to know your opinion on as you would to put various HitEffects , like when you reach the concrete make a different sound and effect of DefaultHit, I need to make several events and call each one in Gun_Shoot script and make tags in the GameManager_Reference script for this to happen or there are other more effective way ?

    Sorry my English is that I am one of the international students of your course, I'm from Brazil .
     
  22. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Thanks I haven't had a chance to try this out but it does look useful. I'll add to the list of contributed code!
     
  23. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Perhaps in the hit effects script you could check what was hit using tags like you are thinking and then spawn an appropriate hit effect. There probably are better ways to do it but I haven't thought of any yet.
     
    Racine-Z likes this.
  24. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
    I've come across a problem with the Destructable_Explode script that I can't figure out. When an exploding barrel is placed on top of another one in the #scene, strange behaviours occur. If the bottom one explodes, none of the other barrels take damage. If the top one explodes, all barrels take damage normally except that the bottom one does not take damage. Oddly enough, it is only the barrels affected. Golems take damage normally in both scenarios.

    I took some screen shots and put them into an Imgur album to show the behaviour. http://imgur.com/a/aipia

    My script does not deviate from the tutorial except that I added the "ProcessDamage" function to the player.

    Code (csharp):
    1.  
    2.         void ExplosionSphere() {
    3.             myTransform.parent = null;
    4.             GetComponent<Collider>().enabled = false;
    5.  
    6.             struckColliders = Physics.OverlapSphere(myTransform.position, explosionRange);
    7.             foreach(Collider col in struckColliders) {
    8.                 distance = Vector3.Distance(myTransform.position, col.transform.position);
    9.                 damageToApply = (int)Mathf.Abs((1 - (distance / explosionRange)) * rawDamage);
    10.                 if (Physics.Linecast(myTransform.position, col.transform.position, out hit)) {
    11.                     if (hit.transform == col.transform || col.GetComponent<Enemy_TakeDamage>() != null) {
    12.                         col.SendMessage("ProcessDamage", damageToApply, SendMessageOptions.DontRequireReceiver);                      
    13.                     }
    14.                 }
    15.  
    16.                 if(col.GetComponent<Rigidbody>() != null) {
    17.                     col.GetComponent<Rigidbody>().AddExplosionForce(explosionForce, myTransform.position, explosionRange, 1, ForceMode.Impulse);
    18.                 }
    19.             }
    20.  
    21.             Destroy(gameObject, 0.05f);
    22.         }
    23.  
    24.  
     
  25. joewode

    joewode

    Joined:
    Dec 3, 2014
    Posts:
    35
    First of all, thanks for doing these tutorials. Personally I've found it extremely helpful.

    I've completed all the chapters up to and including the item chapter. I'm having an issue in my project though, and I need a little help. Here's the problem I am having:

    I've gotten the item system to work, everything functions, but the inventory is broken. When I pick up items, the inventory generates a button, names it correctly, etc. However, clicking on it does nothing. The button doesn't respond to being clicked or to being moused over. For whatever reasons it seems the onclick function isn't being assigned.

    I've gone over the code several times, both in the Player_Inventory script (which is where I thought the problem was) as well as the Item_Pickup script and the Item_Master script. Everything seems correct. The console flips no errors. I can't figure it out. I even went back and remade the inventory UI just in case I'd messed it up somehow.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine.UI;
    5.  
    6. namespace G5
    7. {
    8.     public class Player_Inventory : MonoBehaviour
    9.     {
    10.  
    11.         public Transform inventoryPlayerParent;
    12.         public Transform inventoryUIParent;
    13.         public GameObject uiButton;
    14.      
    15.         private Player_Master playerMaster;
    16.         private GameManager_ToggleInventoryUI inventoryUIScript;
    17.         private float timeToPlaceInHands = 0.1f;
    18.         private Transform currentlyHeldItem;
    19.         private int counter;
    20.         private string buttonText;
    21.         private List<Transform> listInventory = new List<Transform>();
    22.      
    23.         void OnEnable()
    24.         {
    25.             SetInitialReferences();
    26.             UpdateInventoryListAndUI();
    27.             CheckIfHandsEmpty();
    28.          
    29.             playerMaster.EventInventoryChanged += UpdateInventoryListAndUI;
    30.             playerMaster.EventInventoryChanged += CheckIfHandsEmpty;
    31.             playerMaster.EventHandsEmpty += ClearHands;
    32.         }
    33.  
    34.         void OnDisable()
    35.         {
    36.             playerMaster.EventInventoryChanged -= UpdateInventoryListAndUI;
    37.         playerMaster.EventInventoryChanged -= CheckIfHandsEmpty;
    38.             playerMaster.EventHandsEmpty -= ClearHands;
    39.         }
    40.      
    41.         void SetInitialReferences()
    42.         {
    43.             inventoryUIScript = GameObject.Find("GameManager").GetComponent<GameManager_ToggleInventoryUI>();
    44.             playerMaster = GetComponent<Player_Master>();
    45.         }
    46.      
    47.         void UpdateInventoryListAndUI()
    48.         {
    49.             counter = 0;
    50.             listInventory.Clear();
    51.             listInventory.TrimExcess();
    52.          
    53.             ClearInventoryUI();
    54.          
    55.             foreach(Transform child in inventoryPlayerParent)
    56.             {
    57.                 if(child.CompareTag("Item"))
    58.                 {
    59.                     listInventory.Add(child);
    60.                     GameObject go = Instantiate(uiButton) as GameObject;
    61.                     buttonText = child.name;
    62.                     go.GetComponentInChildren<Text>().text = buttonText;
    63.                     int index = counter;
    64.                     go.GetComponent<Button>().onClick.AddListener(delegate { ActivateInventoryItem(index); });
    65.                     go.GetComponent<Button>().onClick.AddListener(inventoryUIScript.ToggleInventoryUI);
    66.                     go.transform.SetParent(inventoryUIParent, false);
    67.                     counter++;
    68.                 }
    69.             }
    70.         }
    71.      
    72.         void CheckIfHandsEmpty()
    73.         {
    74.             if(currentlyHeldItem == null && listInventory.Count > 0)
    75.             {
    76.                 StartCoroutine(PlaceItemInHands(listInventory[listInventory.Count - 1]));
    77.             }
    78.         }
    79.      
    80.         void ClearHands()
    81.         {
    82.             currentlyHeldItem = null;
    83.         }
    84.      
    85.         void ClearInventoryUI()
    86.         {
    87.             foreach(Transform child in inventoryUIParent)
    88.             {
    89.                 Destroy(child.gameObject);
    90.             }
    91.         }
    92.      
    93.         public void ActivateInventoryItem(int inventoryIndex)
    94.         {
    95.             DeactivateAllInventoryItems();
    96.             StartCoroutine(PlaceItemInHands(listInventory[inventoryIndex]));
    97.         }
    98.      
    99.         void DeactivateAllInventoryItems()
    100.         {
    101.             foreach(Transform child in inventoryPlayerParent)
    102.             {
    103.                 if(child.CompareTag("Item"))
    104.                 {
    105.                     child.gameObject.SetActive(false);
    106.                 }
    107.             }
    108.         }
    109.      
    110.         IEnumerator PlaceItemInHands(Transform itemTransform)
    111.         {
    112.             yield return new WaitForSeconds(timeToPlaceInHands);
    113.             currentlyHeldItem = itemTransform;
    114.             currentlyHeldItem.gameObject.SetActive(true);
    115.         }
    116.     }
    117. }
    118.  
    119.  
    Am I blind or something? Are there some other scripts I should check that could potentially be causing this problem?
     
  26. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
    If you're looking at the inspector on the Button(clone) object, the OnClick() list is always empty.
    I compared your script to mine and they are exactly the same. When you throw an item, does the next item in your inventory activate?
     
  27. joewode

    joewode

    Joined:
    Dec 3, 2014
    Posts:
    35
    Yes it does. Everything works fine besides the inventory menu. I figured the onclick list would stay empty because it doesn't add the listeners until you try to click on the button. So I can pick up items and throw them, the rigidbodies and colliders all behave like they should. The name, tag, and set layer scripts work fine. I just cant use the menu to select which object I want to be active.

    I was worried that the problem wasn't in this script, but I can't figure out which of the other scripts might be causing this either as they also seem to be correct. It's like unity is somehow blind to or just ignores the lines of code that add the listeners. I don't get it.
     
  28. joewode

    joewode

    Joined:
    Dec 3, 2014
    Posts:
    35
    Ok, wait. Nevermind. I forgot that the new UI doesn't work without an EventSystem object. It totally works now.
     
  29. AffreuxLex

    AffreuxLex

    Joined:
    Apr 1, 2016
    Posts:
    6
    I found another bug. If you open your inventory and change items while a gun is reloading, the isReloading boolean doesn't get reset on the Gun_Master. I don't know if there was an event I should have called but for now I just threw a quick check into the OnEnable() method since it is called each time you switch to the gun.
    Code (csharp):
    1.  
    2.             if (gunMaster.isReloading) {
    3.                 ResetGun();
    4.             }
    5.  
     
    Racine-Z likes this.
  30. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436

    The linecast is being blocked by some other collider. It can't be the destructible object because you can see the collider being deactivated to begin with. If you have shards then set them to an Ignore Raycast layer perhaps.

    Thanks, good pickup. That is a bug and your solution looks sound
     
  31. Racine-Z

    Racine-Z

    Joined:
    Dec 10, 2015
    Posts:
    4
    Hello , thanks for the reply and is working , my only problem is that the bullet holes are not facing the right direction , they are facing up , but is working hehehehe and I have 2 questions , the way you handle the animations , I can using the same system to put arms (like FPS)?, and will have something about weapons management like CS.GO , COD or instant access bar DAYZ_SA ! ?

    Thanks for Many great tutorials !!!
     
  32. odawa87

    odawa87

    Joined:
    Mar 14, 2016
    Posts:
    4
    Hey, thanks for the awesome tutorials! Really appreciate them.

    But.. I have a problem I can't seem to fix. So any help would be awesome..
    Problem is in the GunAmmo Script, which just cannot find the player_master or player_ammobox so I get nullreference exceptions.

    Code (csharp):
    1.  
    2.   void Start()
    3.   {
    4.       SetInitialReferences();
    5.       StartCoroutine(UpdateAmmoUIWhenEnabled());
    6.  
    7.       if (basePlayer != null)
    8.       {
    9.           Debug.Log("basePlayer not null");
    10.           basePlayer.EventAmmoChanged += UIAmmoUpdateRequest;
    11.       }
    12.  
    13.       if (ammoBox != null)
    14.       {
    15.           Debug.Log("ammobox not null");
    16.       }
    17.   }
    18.  
    The if statements never get executed, I set the code execution order so GunAmmo sure gets called after basePlayer and ammobox.. Any idea what else I could do?
     
  33. Racine-Z

    Racine-Z

    Joined:
    Dec 10, 2015
    Posts:
    4

    You can put the enteiro code because it has no way of knowing where it is wrong, at least I do not !!! hehehe !!!

    Only the Gun_Ammo!!
     
  34. odawa87

    odawa87

    Joined:
    Mar 14, 2016
    Posts:
    4
    Ha true! While I attempted to paste it I went through the code again and found this..

    Code (csharp):
    1.  
    2.   void SetInitialReferences()
    3.   {
    4.     ....
    5.     ....
    6.  
    7.      if (basePlayer != null)
    8.      {
    9.           basePlayer = GM_References.PLAYER.GetComponent<BasePlayer>();
    10.           ammoBox = GM_References.PLAYER.GetComponent<PlayerAmmoBox>();
    11.      }
    12.   }
    13.  
    Of course it can't find the reference! Silly me.. dont go bughunting late nights.. :D
    Anyway thanks!
     
    Racine-Z likes this.
  35. Torrey

    Torrey

    Joined:
    Jan 22, 2016
    Posts:
    13
    Thank you for helping me with the coding and forming a game that was my own Screenshot_2016-04-18-15-53-01[1].png
     
  36. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    It is possible and you'll see in one of the posts on this forum thread a user who implemented arms. But it is a lot of work and you'll have to figure a lot out.

    I haven't been planning to make an instant access bar because I'm thinking of using left ctrl to bring up the menu. It'll make it a lot easier to throw items quickly at enemies, or I might make a system modification later where there are groups that you can cycle through quickly with the 1,2,3 keys. For example repeatedly pressing 2 will cycle through only guns in your inventory, pressing 1 will cycle through melee weapons, 3 will cycle through throwing objects that aren't guns or melee.

    LOL, maybe that's how you have to write secret bits of code in Robot AI so that humans can still hack into them and make them self destruct before they turn into terminators... :D
     
  37. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Fantastic work! That's an excellent accomplishment
     
  38. K_Kaze

    K_Kaze

    Joined:
    Apr 30, 2016
    Posts:
    1
    Hello, i have done my assignment and did my best to do every thing on the list
    Enjoy:D
     
  39. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    A, nice low poly environment!
    Thanks for sharing!
     
  40. Deleted User

    Deleted User

    Guest

    Hello guys. I have written a script for aiming down the sight

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. namespace FPSSystem
    5. {
    6.     public class Ironsight : MonoBehaviour {
    7.         public Camera weaponCam;
    8.         public Vector3 aimPosition;
    9.         public Vector3 normalPosition;
    10.         public GameObject weaponGameObject;
    11.         public string buttonName;
    12.  
    13.  
    14.         void Start ()
    15.         {
    16.             if(weaponCam == null)
    17.             {
    18.                 Debug.LogWarning("Camera not assigned in \"Ironsight\" script. The script will be disabled");
    19.                 this.enabled = false;
    20.             }
    21.         }
    22.  
    23.         void Update ()
    24.         {
    25.             //if (Input.GetMouseButton(1))
    26.             if (Input.GetButton(buttonName))
    27.             {
    28.                 weaponGameObject.transform.localPosition = Vector3.Lerp(weaponGameObject.transform.localPosition, aimPosition, Time.deltaTime * 8);
    29.                 weaponCam.fieldOfView = Mathf.Lerp(weaponCam.fieldOfView, 45, Time.deltaTime * 10);
    30.             }
    31.             else
    32.             {
    33.                 weaponGameObject.transform.localPosition = Vector3.Lerp(weaponGameObject.transform.localPosition, normalPosition, Time.deltaTime * 8);
    34.                 weaponCam.fieldOfView = Mathf.Lerp(weaponCam.fieldOfView, 60, Time.deltaTime * 10);
    35.             }
    36.         }
    37.     }
    38. }
    39.  
    40.  
    Script is very easy to understand.
     

    Attached Files:

    Last edited by a moderator: May 1, 2016
  41. Deleted User

    Deleted User

    Guest

    Here is a Crouch script that I've translated from JS & works pretty well for me. You can write a crawl script from this as well.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. namespace FPSSystem
    5. {
    6.     public class Crouch : MonoBehaviour {
    7.  
    8.         public float crouchSpeed = 3;
    9.         CharacterController charController;
    10.         public Transform Player;
    11.         private float charHeight;
    12.         private Vector3 pos;
    13.  
    14.  
    15.         void Start()
    16.         {
    17.             Player = transform;
    18.             charController = GetComponent<CharacterController>();
    19.             charHeight = charController.height;
    20.         }
    21.  
    22.         void Update()
    23.         {
    24.             float h = charHeight;
    25.  
    26.             if (Input.GetKey(KeyCode.C))
    27.             {
    28.                 h = 1;
    29.             }
    30.             float lastHeight = charController.height;
    31.             charController.height = Mathf.Lerp(charController.height, h, Time.deltaTime * 5);
    32.             pos.x = Player.position.x;
    33.             pos.z = Player.position.z;
    34.             pos.y = Player.position.y + (charController.height - lastHeight) / 2;
    35.             Player.position = pos;
    36.         }
    37.     }
    38. }
    39.  
    40.  
     

    Attached Files:

    Last edited by a moderator: May 1, 2016
  42. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Try putting your code in LateUpdate rather than Update and see how that behaves with the animation
     
    Deleted User likes this.
  43. Deleted User

    Deleted User

    Guest

    The problem is solved sir. Actually it was conflicting with my WeaponSway effect script. I removed that script & aiming works fine. :)
     
  44. Saurabh-Saralaya

    Saurabh-Saralaya

    Joined:
    Apr 28, 2016
    Posts:
    23
    How do i make the Player's camera relative to the player's facing direction.

    The thing is i want to place the player on top of a tower facing the scene, since this requires me to alter the rotation of the player / playerCamera. But if i did this whole of camera of player is altered and whenever i move around the scene i have a tilted camera.

    I tried change around the Pivot/ Center tool and Global/Local tool at the top of title bar, but there were no difference in the result
     
  45. Saurabh-Saralaya

    Saurabh-Saralaya

    Joined:
    Apr 28, 2016
    Posts:
    23
    I have also tried changing the rotation and position at the child object of FPS controller, well that results in the camera placed over the ear of the Character
     
  46. Saurabh-Saralaya

    Saurabh-Saralaya

    Joined:
    Apr 28, 2016
    Posts:
    23
    Last edited: May 3, 2016
  47. Torrey

    Torrey

    Joined:
    Jan 22, 2016
    Posts:
    13
    Ok so how would i go about making my cursor appear on the next scence i go to because i have a wall that is set on tigger enter then you go to the next scence problem is i need my cursor because i need to see where it is to answer questions now how would i do that. and i still can not figure out how to have the score transfer over from level to level. i do not know if you will be able to expain it to me but i figured i would see if you could help. it would be much appreciated if you could. Maybe dumb it down a lot i will really try to understand it but it can be difficult and thank you
     
  48. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Just capture the rotation values before you do whatever you're doing and then when you're finished apply that rotation back.
     
  49. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Use playerprefs to store bits of data. When the new scene is loaded set the cursor and other things to whatever you need. Go read the script reference for playerprefs and scenemanager
     
  50. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    A+ for a really solid effort!
    The music and sounds were starting to hurt my head but the effort was obvious and the setting interesting!