Function in Unity3d(c#) doesnt work correctly - c#

I try to creacte some buildings in 2d, but it should not be touched with the other buildings.I have a
private GameObject building;
From Update i called function
buildFence(Vector2 nextPos)
where i create new building
And from this function i called function which must return boolean type
public bool canbuild()
{
//Debug.Log(building);
if (building.GetComponent<Rigidbody2D>().IsTouchingLayers(LayerMask.GetMask("Buildings")))
{
building.GetComponent<SpriteRenderer>().color = Color.red;
//Debug.Log("canb=false");
return false;
}
else {
building.GetComponent<SpriteRenderer>().color = Color.green;
return true;
}
}
but this function always return true. If i called the same function from Update,
everything works well.
All code here
void Update()
{
if (mode)
{
if (TEST)
{
if (!UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButtonDown(0) && idBuilding != 0 && buildFlag)
{
buildFlag = false;
startpos = cam.ScreenToWorldPoint(Input.mousePosition);
if (idBuilding != 1)
{
building = (GameObject)Instantiate(buildings[idBuilding - 1], startpos, new Quaternion(0, 0, 0, 0));
building.GetComponent<Collider2D>().isTrigger = true;
canbuild();
}
else
{
}
}
if (Input.GetMouseButton(0) && idBuilding != 0)
{
if (idBuilding != 1)
{
Vector2 pos = cam.ScreenToWorldPoint(Input.mousePosition);
building.transform.position = pos;
canbuild();
}
else
{
buildFence(cam.ScreenToWorldPoint(Input.mousePosition));
if (!canbuild())
{
Debug.Log("succes");
}
}
}
if (Input.GetMouseButtonUp(0) && idBuilding != 0)
{
if (canbuild())
{
buildFlag = false;
Vector2 viewportPoint = Camera.main.WorldToViewportPoint(building.transform.position + new Vector3(2, 2, 0));
bAccept.anchorMin = viewportPoint;
bAccept.anchorMax = viewportPoint;
bAccept.gameObject.active = true;
}
else
{
Debug.Log("CantBuild");
Destroy(building);
buildFlag = true;
}
//building.GetComponent<Collider2D>().enabled = true;
}
}
}
else
{
}
}
}
void buildFence(Vector2 nextPos)
{
Vector2 delta = nextPos - startpos;
//Debug.Log("v2" + (nextPos - startpos));
//Debug.Log("v2.angle="+ Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
//Debug.Log("v2.angle=" +);
if (delta.magnitude >= 2.55 && canBuildNext)
{
if (delta.x < 0)
building = (GameObject)Instantiate(buildings[0], startpos, Quaternion.Euler(0, 0, Vector2.Angle(new Vector2(x, y), (nextPos - startpos))));
else
building = (GameObject)Instantiate(buildings[0], startpos, Quaternion.Euler(0, 0, -Vector2.Angle(new Vector2(x, y), (nextPos - startpos))));
building.GetComponent<Collider2D>().isTrigger = true;
canBuildNext = false;
}
if (!canBuildNext)
{
if (!canbuild(ref building))
{
Debug.Log("HERE");
if (delta.x < 0)
building.transform.rotation = Quaternion.Euler(0, 0, Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
else
building.transform.rotation = Quaternion.Euler(0, 0, -Vector2.Angle(new Vector2(x, y), (nextPos - startpos)));
}
else
{
startpos = nextPos;
//building.GetComponent<Collider2D>().isTrigger = false;
Zabor.Push(building);
canBuildNext = true;
}
}
}
public bool canbuild()
{
//Debug.Log(b);
//Debug.Log(building);
if (building.GetComponent<Rigidbody2D>().IsTouchingLayers(LayerMask.GetMask("Buildings")))
{
building.GetComponent<SpriteRenderer>().color = Color.red;
//Debug.Log("canb=false");
buildfail = false;
return false;
}
else {
building.GetComponent<SpriteRenderer>().color = Color.green;
buildfail = true;
return true;
}
}

Related

Why transform.eulerAngles doesn't rotate my player?

i have a little problem with this game i'm working in, the problem is that the player object isn't rotating with the code i'm using, and it used to work before, idk why, it was working well and i tested several times it's very simple here is the code.
Edit. I just posted the all code of the controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;
public float speed;
public float runSpeed;
public float jumpForce;
private float moveInput;
private Vector3 rotation;
public bool isGrounded;
private bool isAlsoTrampoline;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
private Animator animator;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private int cState = 1;
private int capsState = 1;
public bool isWalking;
public bool isRunning;
public bool isCrunching;
public bool isSliding;
public bool isGraping;
public Vector3 climbPos;
private PortalDetector portalName;
private Transform otherPortal;
private int colorPortal = 0;
private GameObject otherPortalPos;
private Vector2 currentY,lastY;
private AudioSource audioStep;
private bool amFalling;
public void Step()
{
audioStep.Play();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Trampoline")
{
isAlsoTrampoline = true;
}
if (collision.tag == "Ledge")
{
Debug.Log("Puedo Trepar esto!!??? ");
if (!isGrounded)
{
isGraping = true;
rb.gravityScale = 0;
rb.velocity = new Vector3(0,0,0);
animator.SetBool("isLedge", true);
climbPos = GetComponent<Transform>().position;
Debug.Log("Trepado!!!!!:DDDDD");
}
}
if (collision.tag == "BluePortal")
{
colorPortal = 1;
}
else if (collision.tag == "OrangePortal")
{
colorPortal = 2;
}
if (collision.tag == "Transporter")
{
if (colorPortal == 1)
{
otherPortal = collision.gameObject.transform.GetChild(3);
}
if (colorPortal == 2)
{
otherPortal = collision.gameObject.transform.GetChild(2);
}
otherPortalPos = otherPortal.transform.gameObject;
transform.position = new Vector3(otherPortalPos.transform.position.x, otherPortalPos.transform.position.y, transform.position.z);
rb.velocity = new Vector3(0, 0, 0);
}
}
void BackToIdle()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x+5,climbPos.y,climbPos.z);
GetComponent<Rigidbody2D>().gravityScale = 10;
animator.SetBool("isLedge", false);
isGraping = false;
}
void ClimbingStepOne()
{
GetComponent<Rigidbody2D>().velocity = new Vector3(climbPos.x, climbPos.y + 5, climbPos.z);
}
void Start()
{
portalName = GetComponent<PortalDetector>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
audioStep = GetComponent<AudioSource>();
currentY = lastY;
}
// Update is called once per frame
void FixedUpdate()
{
if (isGrounded && !isGraping)
{
if (isWalking)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
if (isCrunching)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * (speed - 1), rb.velocity.y);
}
}
if (isRunning && !isCrunching && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
if (isRunning && isSliding && !isGraping)
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * runSpeed, rb.velocity.y);
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
currentY = new Vector2(transform.position.x, transform.position.y);
if (Input.GetKey(KeyCode.UpArrow) && isGraping)
{
animator.SetBool("isClimbing", true);
}
if (!isGrounded && isAlsoTrampoline)
{
animator.SetBool("isFalling", true);
}
else
{
isAlsoTrampoline = false;
animator.SetBool("isFalling", false);
}
if (Input.GetKeyUp(KeyCode.CapsLock) && !isCrunching)
{
capsState *= -1;
if (capsState < 0 && moveInput == 0)
{
isWalking = false;
isRunning = true;
jumpForce = 14f;
}
else if(capsState > 0 && moveInput == 0)
{
isWalking = true;
isRunning = false;
jumpForce = 7f;
}
else if (capsState < 0 && moveInput != 0)
{
isWalking = false;
isRunning = true;
animator.SetBool("isRunning", true);
animator.SetBool("isWalking", false);
jumpForce = 14f;
}
else if (capsState > 0 && moveInput != 0)
{
isWalking = true;
isRunning = false;
animator.SetBool("isRunning", false);
animator.SetBool("isWalking", true);
jumpForce = 7f;
}
}
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (moveInput == 0)
{
animator.SetBool("isWalking", false);
animator.SetBool("isRunning", false);
}
else
{
if (isWalking)
{
animator.SetBool("isWalking", true);
}
if (isRunning)
{
animator.SetBool("isRunning", true);
}
}
if(isGrounded && Input.GetKeyUp(KeyCode.C))
{
cState *= -1;
if (isRunning)
{
if (cState < 0)
{
StartCoroutine (IsSliding());
cState *= -1;
}
else if (cState > 0)
{
StartCoroutine(IsSliding());
cState *= -1;
}
}
else
{
isRunning = false;
isWalking = true;
if (cState < 0)
{
animator.SetBool("isCrunching", true);
isCrunching = true;
}
else if (cState > 0)
{
animator.SetBool("isCrunching", false);
isCrunching = false;
}
}
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
animator.SetTrigger("takeOf");
}
if (isGrounded)
{
animator.SetBool("onGround", true);
animator.SetBool("isFalling", false);
amFalling = false;
}
else
{
if ((currentY.y < lastY.y - 2) && amFalling == false)
{
lastY = currentY;
animator.SetBool("isFalling", true);
amFalling = true;
}
animator.SetBool("onGround", false);
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
isJumping = false;
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
IEnumerator IsSliding()
{
isSliding = true;
isRunning = true;
isWalking = false;
animator.SetBool("isCrunching", true);
yield return new WaitForSecondsRealtime(.5f);
animator.SetBool("isCrunching", false);
animator.SetBool("isRunning", true);
isSliding = false;
}
}
i just made a debug.log and this is the result
Move Input Val:1 Moving right, eulerAngle:(0.0, 0.0, 0.0)rotation:(0.0, 0.0, 0.0, 1.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:210)
Move Input Val:-1 Moving left, eulerAngle: (0.0, 180.0, 0.0)rotation:(0.0, 1.0, 0.0, 0.0)
UnityEngine.Debug:Log(Object)
PlayerController:Update() (at Assets/Scripts/PlayerController.cs:215)

How to find which collider with same tag is touching my character firstly when multiple colliders are touching my character same time

I'm trying to figure out which collider with same tag is touching my character firstly when multiple colliders are touching my character same time.
if (col.transform.gameObject.tag == "enemy") {
hit = true;
rgd.AddForce(new Vector2(0, 2.150f), ForceMode2D.Impulse);
if (transform.position.x-col.transform.gameObject.transform.position.x < 0)
{
rgd.AddForce(-1*rgd.transform.right * 40);
}
else
{
rgd.AddForce(1*rgd.transform.right * 40);
}
if (Mathf.Approximately (angle, 0)) {
Destroy (col.transform.gameObject);
damage = 0;
} else {
damage = 25;
}
enemydamageSound.Play();
}
I solved it by adding a few code.Here is my new code:
private int jumpCount = 0;
if (col.transform.gameObject.tag == "ground")
{
isGround = true;
jumpped = true;
jumpCount = 0;
}
if (col.transform.gameObject.tag == "enemy")
{
hit = true;
if (!isGround && jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2.150f), ForceMode2D.Impulse);
jumpCount++;
}
if (transform.position.x - col.transform.gameObject.transform.position.x < 0)
{
if (jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2f), ForceMode2D.Impulse);
}
rgd.AddForce(-1 * rgd.transform.right * 40);
}
else
{
if (jumpCount == 0)
{
rgd.AddForce(new Vector2(0, 2f), ForceMode2D.Impulse);
}
rgd.AddForce(1 * rgd.transform.right * 40);
}
if (Mathf.Approximately(angle, 0))
{
Destroy(col.transform.gameObject);
damage = 0;
}
else
{
damage = 25;
}
enemydamageSound.Play();
}

move a gameobject position in a slow motion unity c#

I wanna move the Camera (GameObject) to be like navigating between panels... Its working well but I want it to be in a slow motion to be like animation. I am using unity and c#.
Thank you for your help
public class moveCanvas : MonoBehaviour
{
Vector3 reset = new Vector3(0, 0, -10);
Vector3 leftpanel = new Vector3(-205.5f, 0, 0);
Vector3 rightpanel = new Vector3(205.5f, 0, 0);
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
GoLeft();
}
if (Input.GetKeyDown(KeyCode.D))
{
GoRight();
}
}
public void GoLeft()
{
Vector3 currentposition = GameObject.Find("Main Camera").transform.position;
if (currentposition == reset)
GameObject.Find("Main Camera").transform.position = leftpanel;
else if (currentposition == rightpanel)
GameObject.Find("Main Camera").transform.position = reset;
else
return;
}
public void GoRight()
{
Vector3 currentposition = GameObject.Find("Main Camera").transform.position;
if (currentposition == reset)
GameObject.Find("Main Camera").transform.position = rightpanel;
else if (currentposition == leftpanel)
GameObject.Find("Main Camera").transform.position = reset;
else
return;
}
I Found the answer
using System.Collections;
using UnityEngine;
public class MoveCanvas : MonoBehaviour
{
private Vector3 _reset = new Vector3(0, 0, -10);
private Vector3 _leftpanel = new Vector3(-205.5f, 0, 0);
private Vector3 _rightpanel = new Vector3(205.5f, 0, 0);
private float _smoothTime = 0.7f;
private Vector3 _velocity = Vector3.zero;
private Vector3 _currentposition;
private int _stoplimit = 2;
void Start()
{
_currentposition = gameObject.transform.position;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(GoLeft());
}
else if (Input.GetKeyDown(KeyCode.D))
{
StartCoroutine(GoRight());
}
}
private IEnumerator GoLeft()
{
if (_currentposition == _reset)
{
while (!Mathf.Approximately(_currentposition.x, _leftpanel.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _leftpanel, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_leftpanel.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _leftpanel;
_currentposition = _leftpanel;
}
else if (_currentposition == _rightpanel)
{
while (!Mathf.Approximately(_currentposition.x, _reset.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _reset, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_reset.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _reset;
_currentposition = _reset;
}
}
private IEnumerator GoRight()
{
if (_currentposition == _reset)
{
while (!Mathf.Approximately(_currentposition.x, _rightpanel.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _rightpanel, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_rightpanel.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _rightpanel;
_currentposition = _rightpanel;
}
else if (_currentposition == _leftpanel)
{
while (!Mathf.Approximately(_currentposition.x, _reset.x))
{
gameObject.transform.position = Vector3.SmoothDamp(_currentposition, _reset, ref _velocity, _smoothTime);
_currentposition = gameObject.transform.position;
if (Mathf.Abs((_currentposition.x) - (_reset.x)) < _stoplimit)
{
break;
}
yield return new WaitForEndOfFrame();
}
gameObject.transform.position = _reset;
_currentposition = _reset;
}
}
}

Can't get my collision to work (platformer) XNA

I'm learning XNA right now and i'm pretty new to programming in general. I'm making a platformer now but when I walk into a platform from left or right I get teleported to the top of the platform. The collision is only working with the last platform added to the platform list.
This is in Game class:
LoadContent:
for (int i = 0; i < 3; i++)
{
platform0List.Add(new Platform0(new Vector2(70 + (i * 300), 400), platform0Texture));
}
Update:
protected override void Update(GameTime gameTime)
{
keyboard = Keyboard.GetState();
player.Update(keyboard, keyboardPrev, platform0List);
foreach (Platform0 platform in platform0List)
{
if (!Move_Free(player.position.X, player.position.Y + player.gravity, player.texture.Width, player.texture.Height, platform.rectangle) && player.gravity >= 0)
{
player.ground = true;
if (player.position.Y + player.texture.Height + player.gravity > platform.position.Y)
{
player.position.Y = platform.position.Y - player.texture.Height;
}
else if (player.position.Y + player.texture.Height + player.gravity < platform.position.Y)
{
player.gravity = platform.position.Y - player.texture.Height;
}
break;
}
else
{
player.ground = false;
}
}
if (keyboard.IsKeyDown(Keys.Escape)) this.Exit();
keyboardPrev = keyboard;
base.Update(gameTime);
}
This is my Move_Free method
public static bool Move_Free(float x, float y, int width, int height, Rectangle rectangle)
{
Rectangle rect = new Rectangle((int)x,(int)y,width,height);
if(rect.Intersects(rectangle))
{
return false;
}
else
{
return true;
}
}
This is in Player class
foreach (Platform0 platform in platform0List)
{
if (keyboard.IsKeyDown(Keys.Right) && Game1.Move_Free(position.X + 5, position.Y, texture.Width, texture.Height, platform.rectangle))
{
moveRight = true;
}
else if (keyboard.IsKeyDown(Keys.Right) && ((position.X + texture.Width - platform.position.X) * -1) > 0)
{
position.X += (position.X + texture.Width - platform.position.X) * -1;
}
else
{
moveRight = false;
}
if (keyboard.IsKeyDown(Keys.Left) && Game1.Move_Free(position.X - 5, position.Y, texture.Width, texture.Height, platform.rectangle))
{
moveLeft = true;
}
else if (keyboard.IsKeyDown(Keys.Left) && position.X - (platform.position.X + platform.texture.Width) > 0)
{
position.X -= position.X - (platform.position.X + platform.texture.Width);
}
else
{
moveLeft = false;
}
}
if (moveRight) position.X += 5;
if (moveLeft) position.X -= 5;
if (keyboard.IsKeyDown(Keys.Up) && ground)
{
gravity = -10;
ground = false;
}
if(ground)
{
gravity = 0;
}
else
{
gravity += 9.8f / 60f;
position.Y += gravity;
}
Each iteration of your forloop overwrites your moveLeft and moveRight variables.
Therefore, only the last platform values will remain.

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