Trying to generate prefabs over and over in semi-random positions - c#

So I made this code in an effort to start making a script that generates bush objects in my scene randomly, however when in runs it only spawns the first bush. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BushSpawner : MonoBehaviour
{
public GameObject bush;
private float x = 0f;
private float y = -.47f;
private float z = 0f;
private int bushCount = 0;
private Vector3 origPos;
private bool xPlus = false;
private bool xMinus = false;
private bool zPlus = false;
private bool zMinus = false;
// Use this for initialization
void Start()
{
SpawnBushes();
}
// Update is called once per frame
void Update()
{
}
void SpawnBushes()
{
Vector3 startPos = new Vector3(x, y, z);
Instantiate(bush, startPos, Quaternion.identity);
bushCount += 1;
while (bushCount < 100)
{
Vector3 checkPos = new Vector3(x, y, z);
Collider[] intersecting = Physics.OverlapSphere(checkPos, 1f);
if (intersecting.Length == 0)
{
//code to run if nothing is intersecting as the length is 0
Instantiate(bush, checkPos, Quaternion.identity);
bushCount += 1;
}
else
{
//code to run if something is intersecting it
RollPos();
}
}
}
void RollPos()
{
if (xPlus == true
&& xMinus == true
&& zPlus == true
&& zMinus == true)
{
int newRoll = Random.Range(1, 4);
if (newRoll == 1)
{
x += 10f;
}
else if (newRoll == 2)
{
x -= 10f;
}
else if (newRoll == 3)
{
z += 10f;
}
else if (newRoll == 4)
{
z -= 10f;
}
xPlus = false;
xMinus = false;
zPlus = false;
zMinus = false;
}
else
{
int roll = Random.Range(1, 4);
if (roll == 1)
{
if (xPlus == false)
{
x += 2f;
xPlus = true;
}
else
{
RollPos();
}
}
if (roll == 2)
{
if (xMinus == false)
{
x -= 2f;
xMinus = true;
}
else
{
RollPos();
}
}
if (roll == 3)
{
if (zPlus == false)
{
z += 2f;
zPlus = true;
}
else
{
RollPos();
}
}
if (roll == 4)
{
if (zMinus == false)
{
z -= 2f;
zMinus = true;
}
else
{
RollPos();
}
}
}
}
}
I tried putting SpawnBushes in Update to run while a bool is true then make it false when SpawnBushes is done, but that creates the first bush, then 99 other bushes in one random position next to it.
If someone can point me in the right direction or tell me I'm completely off-base I would appreciate it immensely!

Ron Beyer pointed out that I didn't have a large enough range in my Random.Range in RollPos(). Thanks again Ron!

Related

How to go back to script after starting Coroutine?

I currently have a script that allows the player to pick up an item and plays an animation. I have a coroutine to wait 1 second before locking the game object to the player's hand. My problem is that my code for dropping the item and throwing it no longer functions. Is there a workaround to solve this problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
bool isgrounded = true;
public Animator animator;
public GameObject Player;
public Rigidbody rb;
public bool inrange;
public int number = 1;
public Transform theDest;
public float thrust = 1.0f;
public float upthrust = 1.0f;
void start()
{
rb = GetComponent<Rigidbody>();
inrange = false;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Player")
{
inrange = true;
}
}
private void OnTriggerExit(Collider other)
{
inrange = false;
}
public void Update()
{
bool isPickUp = animator.GetBool("isPickUp");
bool pickuppressed = Input.GetKey("e");
if (isgrounded == true)
{
if (pickuppressed && !isPickUp && inrange==true)
{
animator.SetBool("isPickUp", true);
}
if (!pickuppressed && isPickUp || inrange == false)
{
animator.SetBool("isPickUp", false);
}
if (Input.GetKeyUp(KeyCode.E) && (number % 2) == 1 && inrange == true )
{
StartCoroutine(waiter());
number = number + 1;
}
else if (Input.GetKeyUp(KeyCode.E) && (number % 2) == 0 && inrange == true)
{
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<BoxCollider>().enabled = true;
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
number = number - 1;
}
else if (Input.GetKey(KeyCode.G) && (number % 2) == 0 && inrange == true)
{
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<BoxCollider>().enabled = true;
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
number = number - 1;
rb.AddForce(Player.transform.forward * thrust);
rb.AddForce(Player.transform.up * upthrust);
}
}
void OnCollisionEnter(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = true;
}
}
//consider when character is jumping .. it will exit collision.
void OnCollisionExit(Collision theCollision)
{
if (theCollision.gameObject.name == "floor")
{
isgrounded = false;
}
}
IEnumerator waiter()
{
yield return new WaitForSeconds(1);
GetComponent<BoxCollider>().enabled = false;
GetComponent<Rigidbody>().useGravity = false;
GetComponent<Rigidbody>().isKinematic = true;
this.transform.position = theDest.position;
this.transform.parent = GameObject.Find("Destination").transform;
}
}
}
Let me know if more information is needed (still new to stack overflow)
Forget about the coroutine and use Time.time to save the time of pickup to a class variable. Then add comparison to the other if branches such as Time.time > pickupTime + 1f.

How and where in the code should I use the loop bool flag to decide if to loop or to make once movement between the waypoints?

The goal is to be able to decide if to loop or to move only once between the waypoints.
I added the loop bool flag for that.
Added the most details I can.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.AI;
public class Move : MonoBehaviour
{
public Transform[] targets;
public LineRenderer lineRenderer;
public float speed;
public bool go = false;
public bool countOrigPosAsWaypoint = true;
public bool startFromFirstPositionOnStart = false;
public bool goForward = true;
public bool loop = true;
private List<Vector3> pos = new List<Vector3>();
private List<Vector3> positions = new List<Vector3>();
private int index = 0;
private List<GameObject> objectsToMoveCopy = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
if (lineRenderer != null)
{
pos = GetLinePointsInWorldSpace();
}
else
{
if (countOrigPosAsWaypoint == true)
{
pos.Add(transform.position);
}
for (int i = 0; i < targets.Length; i++)
{
pos.Add(targets[i].position);
}
}
if (startFromFirstPositionOnStart == true)
{
transform.position = pos[index];
}
if (pos.Count <= 1)
{
Debug.LogWarning("Targets list count must be more then 1");
}
}
List<Vector3> GetLinePointsInWorldSpace()
{
positions = new Vector3[lineRenderer.positionCount].ToList();
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(positions.ToArray());
//the points returned are in world space
return positions;
}
// Update is called once per frame
void Update()
{
if (go == true && pos.Count > 1)
{
Moving();
}
}
void Moving()
{
Vector3 newPos = transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Count - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
transform.position = newPos;
}
}
If true make a loop between the waypoints either backward or forward and if false just move forward or backward once and stop the last/first waypoint.
I'ld say e.g. at
if (!atLastOne)
{
index++;
}
else if(!loop)
{
stillTraveling = false;
}
else
{
index--;
goForward = false;
}
and accordingly
if (!atFirstOne)
{
index--;
}
else if(!loop)
{
stillTraveling = false;
}
else
{
index++;
goForward = true;
}
And probably remove the current
else
{
stillTraveling = false;
}
as it will be the case most of the time between the points.
In general though: Currently this will all happen in one single frame without any animation... This should probably rather happen in a Coroutine or only do one step at a time .. not in a while loop at all.

How can I move each object in his turn using time to start each object to move?

The goal is to use a time variable for example if the variable int value is 5 then each 5 seconds another object will start moving on the positions.
Now with the loop inside the Move method :
for (int i = 0; i < objectsToMove.Count; i++)
All the objects are moving at the same time but I want to make some kind of queue logic so each N seconds another object will start moving on the positions.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class MoveOnCurvedLines : MonoBehaviour
{
public LineRenderer lineRenderer;
public List<GameObject> objectsToMove = new List<GameObject>();
public float speed;
public bool go = false;
public bool moveToFirstPositionOnStart = false;
private Vector3[] positions;
private Vector3[] pos;
private int index = 0;
private bool goForward = true;
// Start is called before the first frame update
void Start()
{
objectsToMove = GameObject.FindGameObjectsWithTag("New Prefab").ToList();
pos = GetLinePointsInWorldSpace();
if (moveToFirstPositionOnStart == true)
{
objectsToMove[0].transform.position = pos[index];
}
}
Vector3[] GetLinePointsInWorldSpace()
{
positions = new Vector3[lineRenderer.positionCount];
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(positions);
//the points returned are in world space
return positions;
}
// Update is called once per frame
void Update()
{
if (go == true)
{
Move();
}
}
void Move()
{
for (int i = 0; i < objectsToMove.Count; i++)
{
Vector3 newPos = objectsToMove[i].transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Length - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
objectsToMove[i].transform.position = newPos;
}
}
}
This is what I tried with InvokeRepeating :
Starting InvokeRepeating in the Start() and cancelled the Move() calling in the Update.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class MoveOnCurvedLines : MonoBehaviour
{
public LineRenderer lineRenderer;
public List<GameObject> objectsToMove = new List<GameObject>();
public float speed;
public bool go = false;
public bool moveToFirstPositionOnStart = false;
private Vector3[] positions;
private Vector3[] pos;
private int index = 0;
private bool goForward = true;
// Start is called before the first frame update
void Start()
{
objectsToMove = GameObject.FindGameObjectsWithTag("New Prefab").ToList();
pos = GetLinePointsInWorldSpace();
if (moveToFirstPositionOnStart == true)
{
objectsToMove[0].transform.position = pos[index];
}
InvokeRepeating("Move", 3f, 0.1f);
}
Vector3[] GetLinePointsInWorldSpace()
{
positions = new Vector3[lineRenderer.positionCount];
//Get the positions which are shown in the inspector
lineRenderer.GetPositions(positions);
//the points returned are in world space
return positions;
}
// Update is called once per frame
void Update()
{
if (go == true)
{
//Move();
}
}
void Move()
{
for (int i = 0; i < objectsToMove.Count; i++)
{
Vector3 newPos = objectsToMove[i].transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Length - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
objectsToMove[i].transform.position = newPos;
}
}
}
int i = 0;
void StartMove()
{
i = 0;
InvokeRepeating(nameof(Move), 3f, 0.1f);
}
void Move()
{
if( i < objectsToMove.Count)
{
Vector3 newPos = objectsToMove[i].transform.position;
float distanceToTravel = speed * Time.deltaTime;
bool stillTraveling = true;
while (stillTraveling)
{
Vector3 oldPos = newPos;
newPos = Vector3.MoveTowards(oldPos, pos[index], distanceToTravel);
distanceToTravel -= Vector3.Distance(newPos, oldPos);
if (newPos == pos[index]) // Vector3 comparison is approximate so this is ok
{
// when you hit a waypoint:
if (goForward)
{
bool atLastOne = index >= pos.Length - 1;
if (!atLastOne) index++;
else { index--; goForward = false; }
}
else
{ // going backwards:
bool atFirstOne = index <= 0;
if (!atFirstOne) index--;
else { index++; goForward = true; }
}
}
else
{
stillTraveling = false;
}
}
objectsToMove[i].transform.position = newPos;
i++;
}
}
Try this one might help you. Here What I did is to remove the for() loop and instead use an if() condition this way You move function will only execute one time only for one object each time Move() get called by InvokeRepeating(). Nove Call StartMove() where/when you want to start moving the objects.

C# Sfml i dont see the mistake?

I dont know why but my jump method does not work. My character can only jump on one single object. The other obstacle haven't any influence on the player. I really don't see my mistake
foreach (RectangleShape obstacles in MoveAtObjectList)
{
MainPlayer.Move(deltaTime, obstacles);
}
foreach (RectangleShape obstacles in JumpAtObjectList)
{
MainPlayer.Jump(deltaTime, obstacles);
break;
}
Draw();
Window.Display();
}
}
}
}
This was part of my main Class, where i call the jump method within a foreach loop. Here in my Payer class I tried to write the jump function.
using SFML.Graphics;
using SFML.System;
using SFML.Window;
namespace Pong3final
{
class Player : RectangleShape
{
float CollisionDistance = 0.5f;
float PlayerSpeed = 50;
float JumpSpeed = 100;
float FallSpeed = 100;
float JumpTimer;
bool JumpBool = false;
bool Fall = true;
public void Jump(float deltaTime, RectangleShape collisionObject)
{
if (Keyboard.IsKeyPressed(Keyboard.Key.Space) && !Fall && CheckCollision(this, collisionObject))
{
JumpBool = true;
}
//Player is jumping
if (JumpBool)
{
JumpTimer += deltaTime;
this.Position -= new Vector2f(0, JumpSpeed) * deltaTime;
if (JumpTimer > 0.5f)
{
JumpBool = false;
Fall = true;
JumpTimer = 0;
}
}
//Player is falling when he doesnt touch anything and he isnt jumping
else if (!CheckCollision(this, collisionObject))
{
Fall = true;
}
//Player is falling
if (!JumpBool && !CheckCollision(this, collisionObject) && Fall)
{
this.Position += new Vector2f(0, FallSpeed) * deltaTime;
if (CheckCollision(this, collisionObject)) //Player stops falling because of a collision with an object
{
Fall = false;
}
}
}
public void Move(float deltaTime, RectangleShape collisionObject)
{
{
Vector2f MovePlayerPosition = Position;
if ((Keyboard.IsKeyPressed(Keyboard.Key.Left) || Keyboard.IsKeyPressed(Keyboard.Key.A)))
{
MovePlayerPosition -= new Vector2f(PlayerSpeed, 0) * deltaTime;
FloatRect collisionOverlap;
if (CheckCollision(this, collisionObject, out collisionOverlap))
{
MovePlayerPosition = MovePlayerPosition + new Vector2f(collisionOverlap.Width + CollisionDistance, 0);
}
}
if (Keyboard.IsKeyPressed(Keyboard.Key.Right) || Keyboard.IsKeyPressed(Keyboard.Key.D))
{
MovePlayerPosition += new Vector2f(PlayerSpeed, 0) * deltaTime;
FloatRect collisionOverlap;
if (CheckCollision(this, collisionObject, out collisionOverlap))
{
MovePlayerPosition = MovePlayerPosition - new Vector2f(collisionOverlap.Width + CollisionDistance, 0);
}
}
Position = MovePlayerPosition;
}
}
public static bool CheckCollision(RectangleShape obj1, RectangleShape obj2, out FloatRect overlap)
{
FloatRect obj1Collider = obj1.GetGlobalBounds();
FloatRect obj2Collider = obj2.GetGlobalBounds();
//Nur die rechte, linke und obere Seite kollidiert
if (obj1Collider.Intersects(obj2Collider, out overlap))
{
return true;
}
overlap = new FloatRect();
return false;
}
public static bool CheckCollision(RectangleShape obj1, RectangleShape obj2)
{
FloatRect obj1Collider = obj1.GetGlobalBounds();
FloatRect obj2Collider = obj2.GetGlobalBounds();
return obj1Collider.Intersects(obj2Collider);
}
}
}
It looks like you are breaking out of your loop after the first iteration, which is resulting in only that first iteration being performed:
foreach (RectangleShape obstacles in JumpAtObjectList)
{
MainPlayer.Jump(deltaTime, obstacles);
break;
}
Remove the break statement from your loop:
foreach (RectangleShape obstacles in JumpAtObjectList)
{
MainPlayer.Jump(deltaTime, obstacles);
}

Cannot call or set a variable from another script in C#

EDIT Full Scripts:
SoldierController Script (removed few variables due to character limitaton). I have declared 1 new variable called DontMove and want this to be called from the ElevatorOpen script. Issue I am having is calling this script even though this is set to static and public.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SoldierController : MonoBehaviour
{
#region Variables
public Transform gunPoint;
public GameObject bulletPrefab;
//Components
protected Animator animator;
private GameObject camera;
private Camera cam;
public GameObject splashFX;
public AudioClip gunShotSound;
//action variables
public static bool dontMove = false;
public float walkSpeed = 1.35f;
bool canwalk = true;
float moveSpeed;
public float runSpeed = 1f;
public float rotationSpeed = 20f;
bool isMoving = false;
public bool walking = true;
bool areWalking;
Vector3 newVelocity;
Vector3 inputVec;
//aiming/shooting variables
bool canAim;
bool canFire = true;
public bool aiming = true;
bool isAiming = false;
public bool grenading = true;
bool isGrenading;
bool canGrenade = true;
int weaponType = 0;
//Weapon Prefabs
GameObject pistol;
GameObject rifle;
GameObject launcher;
GameObject heavy;
#endregion
#region Initialization
void Start()
{
canMove = true;
//dontMove = false;
//set the animator component
animator = GetComponentInChildren<Animator>();
//sets the weight on any additional layers to 1
if (animator.layerCount >= 2)
{
animator.SetLayerWeight(1, 1);
}
//Get the camera
camera = GameObject.FindGameObjectWithTag("MainCamera");
cam = camera.GetComponent<Camera>();
//sets the Weapon to 1 in the animator
weaponType = 1;
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
#endregion
#region Update
void Update()
{
x = Input.GetAxisRaw("Horizontal");
//z = Input.GetAxisRaw("Vertical");
inputVec = new Vector3(x, 0, z);
if (animator)
{
CoverUpdate();
JumpingUpdate();
if (!isSwimming) //character can't do any actions while swimming
{
if (Input.GetKeyDown(KeyCode.LeftControl) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetMouseButtonDown(0) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetButton("Fire2") && canAim && aiming)
{
isAiming = true;
}
else
{
isAiming = false;
}
}
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
if (!isSwimming) //character is not swimming
{
//gravity
GetComponent<Rigidbody>().AddForce(0, gravity, 0, ForceMode.Acceleration);
if (aircontrol)
AirControl();
//check if we aren't in cover and can move
if (!covered && canMove)
{
if (canPushPull)
{
if (!isPushPulling)
moveSpeed = UpdateMovement(); //if we are not pushpull use normal movement speed
else
moveSpeed = PushPull(); //we are push pulling, use pushpullspeed
}
else
moveSpeed = UpdateMovement();
}
}
else //character is swimming
{
moveSpeed = Swimming();
}
}
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).x;
float velocityZel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if we are moving, set our animator
if (moveSpeed > 0)
{
isMoving = true;
animator.SetBool("Moving", true);
}
else
{
isMoving = false;
animator.SetBool("Moving", false);
}
}
#endregion
void RotateTowardsMovementDir()
{
// Rotation
if (inputVec != Vector3.zero && !isAiming)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
#region UpdateMovement
float UpdateMovement()
{
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//apply velocity based on platform speed to prevent sliding
float platformVelocity = platformSpeed.magnitude * .4f;
Vector3 platformAdjust = platformSpeed * platformVelocity;
//set speed by walking / running
if (areWalking)
{
canAim = false;
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * walkSpeed + platformAdjust;
}
else
{
newVelocity = motion * walkSpeed + platformAdjust;
}
}
else
{
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * runSpeed + platformAdjust;
}
else
{
newVelocity = motion * runSpeed + platformSpeed;
}
}
}
else
{
//if we are falling use momentum
newVelocity = GetComponent<Rigidbody>().velocity;
}
// limit velocity to x and z, by maintaining current y velocity:
newVelocity.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = newVelocity;
if (!isAiming)
RotateTowardsMovementDir();
//if the right mouse button is held look at the mouse cursor
if (isAiming)
{
//make character point at mouse
Quaternion targetRotation;
float rotationSpeed = 40f;
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
//calculate the rolling time
rollduration -= rolldamp;
if (rollduration > 0)
{
isRolling = true;
}
else
{
isRolling = false;
}
if (isRolling)
{
Vector3 localforward = transform.TransformDirection(0, 0, 1);
GetComponent<Rigidbody>().velocity = localforward * rollSpeed;
}
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region AirControl
void AirControl()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//allow some control the air
GetComponent<Rigidbody>().AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
#endregion
#region Swimming
float Swimming()
{
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using swimSpeed
GetComponent<Rigidbody>().AddForce(motion * swimSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
RotateTowardsMovementDir();
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region PushPull
float PushPull()
{
//set bools
canAim = false;
canAbility = false;
canCover = false;
canFire = false;
canGrenade = false;
canItem = false;
canJump = false;
canMelee = false;
canReload = false;
canRoll = false;
canSignal = false;
canwalk = false;
isPushPulling = true;
animator.SetBool("PushPull", true);
Vector3 motion = inputVec;
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using pushpull speed
GetComponent<Rigidbody>().velocity = motion * pushPullSpeed;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Grounding
void CheckForGrounded()
{
float distanceToGround;
float threshold = .45f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
isGrounded = true;
//moving platforms
if (hit.transform.tag == "Platform")
{
//get platform script from collided platform
Platform platformScript = hit.transform.GetComponent<Platform>();
//check if the platform is moved with physics or if it is animated and get velocity from it
if (platformScript.animated)
{
platformSpeed = platformScript.velocity;
platformAnimated = true;
}
if (!platformScript.animated)
{
platformSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
}
//get the platform rotation to pass into our character when they are on a platform
platformFacing = hit.transform.rotation;
}
else
{
//if we are not on a platform, reset platform variables
platformSpeed = new Vector3(0, 0, 0);
platformFacing.eulerAngles = new Vector3(0, 0, 0);
Platform platformScript = null;
float platformVelocity = 0f;
}
}
else
{
isGrounded = false;
}
}
}
#endregion
#region Cover
void CoverUpdate()
{
/*
if (covering && !isSwimming)
{
//check if we press cover button
if (Input.GetButtonDown("Cover") && canCover && !covered)
{
//set variables
animator.SetBool("Moving", false);
Input.ResetInputAxes();
isMoving = false;
animator.SetBool("Moving", false);
covered = true;
canReload = true;
canCover = false;
canItem = false;
canMelee = false;
canFire = false;
canItem = false;
canGrenade = false;
canJump = false;
cover = 1;
animator.SetInteger("Cover", 1);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
else
{
//if we are already in cover and press the cover button, get out of cover
if (Input.GetButtonDown("Cover") && covered == true)
{
//set the animation back to idle
animator.SetInteger("Cover", 3);
//set variables
cover = 0;
covered = false;
canCover = true;
canAbility = true;
canAim = true;
canItem = true;
canGrenade = true;
canFire = true;
}
}
}*/
}
#endregion
#region Jumping
void JumpingUpdate()
{
if (!isSwimming) //if character is not swimming
{
//If the character is on the ground
if (isGrounded)
{
//set the animation back to idle
animator.SetInteger("Jumping", 0);
//set variables
jumped = false;
//check if we press jump button
if (canJump && Input.GetButtonDown("Jump") && cover != 1)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
animator.SetInteger("Jumping", 2);
}
}
else
{
//set bools
canDoubleJump = true;
if (!falling && !jumped)
{
//set the animation back to idle
animator.SetInteger("Jumping", 2);
falling = true;
}
//if double jumping is allowed and jump is pressed, do a double jump
if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && doublejumped != true && doublejumping)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += doublejumpSpeed * Vector3.up;
//set the animation to double jump
animator.SetInteger("Jumping", 3);
//set variables
canJump = false;
doublejumped = true;
isJumping = true;
falling = false;
jumped = false;
}
}
}
else //characer is swimming
{
//check if we press jump button
if (canSwim && Input.GetButtonDown("Jump"))
{
if (x != 0 || z != 0) //if the character movement input is not 0, swim in facing direction
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += swimBurstSpeed * transform.forward;
animator.SetTrigger("SwimBurst");
}
else //we are not trying to move the character, jump up
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity = jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
canJump = false;
isJumping = true;
canDoubleJump = true;
jumped = true;
animator.SetInteger("Jumping", 2);
}
}
}
}
#endregion
#region Misc Methods
void Rolling()
{
StartCoroutine(COPlayOneShot("Rolling"));
covered = false;
canCover = false;
cover = 0;
animator.SetInteger("Cover", 0);
isRolling = true;
}
void Fire()
{
StartCoroutine(COPlayOneShot("Fire"));
(Instantiate(bulletPrefab, gunPoint.position, transform.root.rotation) as GameObject).GetComponent<BulletController>().damage = 20;
StartCoroutine(WeaponCooldown());
GetComponent<AudioSource>().PlayOneShot(gunShotSound);
}
IEnumerator WeaponCooldown()
{
canFire = false;
yield return new WaitForSeconds(0.1f);
canFire = true;
}
void Ability()
{
StartCoroutine(COPlayOneShot("Ability"));
}
void Item()
{
StartCoroutine(COPlayOneShot("Item"));
}
void Grenade()
{
StartCoroutine(COGrenade());
isGrenading = true;
}
void Reload()
{
StartCoroutine(COReload(weaponType));
isReloading = true;
}
void Signal()
{
StartCoroutine(COPlayOneShot("Signal"));
}
void Melee()
{
StartCoroutine(COMelee());
isMelee = true;
}
void Pain()
{
StartCoroutine(COPlayOneShot("Pain"));
}
//plays a random death# animation between 1-3
void Death()
{
//stop character movement
animator.SetBool("Moving", true);
Input.ResetInputAxes();
isMoving = false;
int deathnumber = 5;
animator.SetInteger("Death", deathnumber);
}
#endregion
#region CORoutines
//function to play a one shot animation
public IEnumerator COPlayOneShot(string paramName)
{
animator.SetBool(paramName, true);
yield return null;
animator.SetBool(paramName, false);
}
//function to switch weapons
public IEnumerator COSwitchWeapon(string weaponname, int weaponnumber)
{
//sets Weapon to 0 first to reset
animator.SetInteger(weaponname, 0);
yield return null;
yield return null;
animator.SetInteger(weaponname, weaponnumber);
}
//function to reload
public IEnumerator COReload(int weapon)
{
//sets Weapon to 0 first to reset
animator.SetBool("Reload", true);
yield return null;
animator.SetBool("Reload", false);
float wait = 0;
if (weaponType == 1 || weaponType == 2)
{
wait = 1.85f;
}
if (weaponType == 3 || weaponType == 4)
{
wait = 3f;
}
yield return new WaitForSeconds(wait);
isReloading = false;
}
//function to grenade
IEnumerator COGrenade()
{
//sets Weapon to 0 first to reset
animator.SetBool("Grenade", true);
yield return null;
animator.SetBool("Grenade", false);
yield return new WaitForSeconds(1);
isGrenading = false;
}
//function to Melee
IEnumerator COMelee()
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = false;
isMoving = false;
animator.SetTrigger("Melee");
yield return new WaitForSeconds(.7f);
isMelee = false;
canMove = true;
}
IEnumerator COKnockback()
{
StartCoroutine(COPlayOneShot("Knockback"));
return null;
}
public IEnumerator CODazed()
{
StartCoroutine(COPlayOneShot("Dazed"));
Debug.Log("Cant Move");
canMove = false;
canFire = false;
canAim = false;
canJump = false;
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
yield return new WaitForSeconds(3.0f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = true;
canFire = true;
canAim = true;
canJump = true;
}
#endregion
#region WeaponSwitching
void WeaponSwitch()
{
weaponType++;
if (weaponType == 1)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
if (weaponType == 2)
{
//enables rifle, disables other weapons
pistol.SetActive(false);
rifle.SetActive(true);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 2));
}
if (weaponType == 3)
{
//enables launcher, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(true);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 3));
}
if (weaponType == 4)
{
//enables heavy, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(true);
StartCoroutine(COSwitchWeapon("Weapon", 4));
}
if (weaponType == 5)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
weaponType = 1;
}
}
#endregion
}
And finally the elevatorOPen script:
using UnityEngine;
using System.Collections;
public class ElevatorOpen : MonoBehaviour
{
private Animator animator;
public AudioClip ElevatorBing;
void Awake ()
{
animator = GetComponent <Animator>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 1);
GetComponent<AudioSource>().PlayOneShot(ElevatorBing);
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 0);
SoldierController.dontMove = true;
}
}
}
This has been addressed. This is a bug with Unity 5 Beta - Spoke to a member of staff who provided me the latest version of Unity, which has fixed the issue.

Categories