Adding Android Mobile Controller to Unity Game - c#

I have been trying for quiet some time now to find out how can I place an android mobile game controller in Unity. The game I have is using the mouse and keyboard buttons to do that but because I want to publish it on Android as well I want to add mobile controllers and I am not very familiar with that.
Here is my PlayerController.cs:
public class PlayerControllerUnity : MonoBehaviour
{
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15.0f;
public float sensitivityY = 15.0f;
public float minimumX = -360.0f;
public float maximumX = 360.0f;
public float minimumY = -89.0f;
public float maximumY = 89.0f;
private float rotationYaxis = 0.0f;
private float rotationXaxis = 0.0f;
private Quaternion originalCameraRotation;
private Quaternion originalPlayerRotation;
public PlayerUnity playerUnity;
private GameObject hand;
private GameObject goInHand;
private CWObject currentObjectInHand;
private Vector3 positionHand_Tile = new Vector3(0.15f, -0.15f, 0.3f);
private Vector3 scaleHand_Tile = new Vector3(0.1f, 0.1f, 0.1f);
private Quaternion rotationHand_Tile = Quaternion.Euler(-15.0f, 0.0f, 15.0f);
private Vector3 positionHand_Item = new Vector3(0.15f, -0.15f, 0.2f);
private Vector3 scaleHand_Item = new Vector3(0.1f, 0.1f, 0.1f);
private Quaternion rotationHand_Item = Quaternion.Euler(0.0f, 55.0f, 0.0f);
private Vector3 positionHand_Current;
private Vector3 scaleHand_Current;
private Quaternion rotationHand_Current;
private bool firstUpdate = true;
public void Start()
{
originalCameraRotation = playerUnity.mainCamera.transform.localRotation;
originalPlayerRotation = transform.localRotation;
hand = new GameObject();
hand.name = "Hand";
hand.transform.parent = playerUnity.mainCamera.transform;
hand.transform.localPosition = positionHand_Tile;
hand.transform.localScale = scaleHand_Tile;
hand.transform.localRotation = rotationHand_Tile;
}
public void UpdateControlled()
{
if (playerUnity.gameManagerUnity.State == GameManagerUnity.GameManagerUnityState.GAME &&
playerUnity.playerGUI.ActiveState == PlayerGUI.State.NORMAL)
{
if (Screen.lockCursor == false)
{
//Auto pause if the user leaves the game for some reason (ALT+TAB, etc..)
playerUnity.gameManagerUnity.Pause();
}
else
{
if (firstUpdate)
{
rotationYaxis = playerUnity.player.rotation.y;
rotationXaxis = playerUnity.player.rotation.x;
firstUpdate = false;
}
if (Input.GetKeyDown(KeyCode.R))
playerUnity.player.ResetPosition();
if (Input.GetKeyDown(KeyCode.C))
playerUnity.ChangeCamera();
UpdateJump();
UpdateMovement();
UpdateCameraRotation();
UpdateUserActions();
UpdateItemOnHand();
playerUnity.player.rotation.y = rotationYaxis;
playerUnity.player.rotation.x = rotationXaxis;
}
}
}
private void ExecuteHandUseAnimation()
{
handUseAnimationTimer = 0.5f;
}
private float handUseAnimationTimer;
private float handMovementTimer;
private void UpdateItemOnHand()
{
if (currentObjectInHand != playerUnity.objectInHand)
{
if (goInHand)
{
playerUnity.gameManagerUnity.objectsManagerUnity.RemoveGameObject(goInHand);
goInHand = null;
}
this.currentObjectInHand = playerUnity.objectInHand;
if (currentObjectInHand != null)
{
goInHand = playerUnity.gameManagerUnity.objectsManagerUnity.CreateGameObjectFromObject(currentObjectInHand);
goInHand.transform.parent = hand.transform;
goInHand.transform.localScale = new Vector3(1, 1, 1);
goInHand.transform.localPosition = new Vector3(0, 0, 0);
goInHand.transform.localRotation = Quaternion.identity;
switch (currentObjectInHand.definition.type)
{
case CWDefinition.DefinitionType.Item:
positionHand_Current = positionHand_Item;
scaleHand_Current = scaleHand_Item;
rotationHand_Current = rotationHand_Item;
break;
case CWDefinition.DefinitionType.Tile:
positionHand_Current = positionHand_Tile;
scaleHand_Current = scaleHand_Tile;
rotationHand_Current = rotationHand_Tile;
break;
}
hand.transform.localPosition = positionHand_Current;
hand.transform.localScale = scaleHand_Current;
hand.transform.localRotation = rotationHand_Current;
}
}
if (handUseAnimationTimer <= 0.0f)
{
if (playerUnity.player.input.moveDirection.magnitude > 0.0f)
{
handMovementTimer += Time.deltaTime;
float deltaY = Mathf.Sin(handMovementTimer * 10) * 0.02f;
float deltaX = Mathf.Sin(handMovementTimer * 10) * 0.01f;
hand.transform.localPosition = positionHand_Current + new Vector3(deltaX, deltaY, 0.0f);
}
else
{
handMovementTimer = 0.0f;
hand.transform.localPosition = positionHand_Current;
}
}
else
{
if (currentObjectInHand != null)
{
float deltaRotation = Mathf.Sin(handUseAnimationTimer * 2.0f * Mathf.PI) * 30;
hand.transform.localPosition = positionHand_Current;
switch (currentObjectInHand.definition.type)
{
case CWDefinition.DefinitionType.Tile:
hand.transform.localRotation = rotationHand_Current * Quaternion.Euler(deltaRotation, 0, 0);
break;
case CWDefinition.DefinitionType.Item:
hand.transform.localRotation = rotationHand_Current * Quaternion.Euler(0, 0, deltaRotation);
break;
}
}
handUseAnimationTimer -= Time.deltaTime;
if (handUseAnimationTimer <= 0.0f)
{
hand.transform.localRotation = rotationHand_Current;
handUseAnimationTimer = 0.0f;
}
}
}
private float userActionCooldown;
private void UpdateUserActions()
{
if (playerUnity.gameManagerUnity.State == GameManagerUnity.GameManagerUnityState.GAME ||
playerUnity.gameManagerUnity.State == GameManagerUnity.GameManagerUnityState.PAUSE)
{
Vector3 cameraPos = playerUnity.transform.position + playerUnity.GetLocalHeadPosition();
Vector3 cameraFwd = playerUnity.mainCamera.transform.forward;
CubeWorld.Utils.Graphics.RaycastTileResult raycastResult = CubeWorld.Utils.Graphics.RaycastTile(
playerUnity.player.world,
GraphicsUnity.Vector3ToCubeWorldVector3(cameraPos),
GraphicsUnity.Vector3ToCubeWorldVector3(cameraFwd),
10.0f,
true, false);
if (userActionCooldown > 0.0f)
userActionCooldown -= Time.deltaTime;
if (userActionCooldown <= 0.0f)
{
if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
{
ExecuteHandUseAnimation();
userActionCooldown = 0.2f;
}
if (raycastResult.hit)
{
if (Input.GetMouseButton(0))
{
if (raycastResult.position.x > 0 && raycastResult.position.x < playerUnity.player.world.tileManager.sizeX - 1 &&
raycastResult.position.z > 0 && raycastResult.position.z < playerUnity.player.world.tileManager.sizeZ - 1 &&
raycastResult.position.y > 0)
{
if (playerUnity.player.world.tileManager.HasTileActions(
raycastResult.position,
TileActionRule.ActionType.CLICKED))
{
playerUnity.player.world.gameplay.TileClicked(raycastResult.position);
}
else
{
if (playerUnity.objectInHand != null)
{
switch (playerUnity.objectInHand.definition.type)
{
case CWDefinition.DefinitionType.Item:
{
playerUnity.gameManagerUnity.fxManagerUnity.PlaySound("hitmetal", playerUnity.player.position);
playerUnity.player.world.gameplay.TileHit(raycastResult.position, ((Item)playerUnity.objectInHand).itemDefinition);
break;
}
default:
playerUnity.gameManagerUnity.fxManagerUnity.PlaySound("hit", playerUnity.player.position);
playerUnity.player.world.tileManager.DamageTile(raycastResult.position, 1);
break;
}
}
}
}
}
else if (Input.GetMouseButton(1))
{
if (playerUnity.objectInHand != null && playerUnity.objectInHand.definition.type == CWDefinition.DefinitionType.Tile)
{
TileDefinition tileDefinition = (TileDefinition) playerUnity.objectInHand.definition;
TilePosition tileCreatePosition = raycastResult.position + CubeWorld.Utils.Graphics.GetFaceNormal(raycastResult.face);
//Don't create tile on top of the world, because no triangles are drawn on the border!
if (tileCreatePosition.y < playerUnity.player.world.tileManager.sizeY - 1 &&
playerUnity.player.world.tileManager.IsValidTile(tileCreatePosition) &&
playerUnity.player.world.tileManager.GetTileSolid(tileCreatePosition) == false)
{
if (playerUnity.player.world.avatarManager.IsTileBlockedByAnyAvatar(tileCreatePosition) == false)
{
playerUnity.player.world.gameplay.CreateTile(tileCreatePosition, tileDefinition.tileType);
playerUnity.player.inventory.RemoveFromDefinition(tileDefinition, 1);
if (playerUnity.player.inventory.HasMoreOfDefinition(tileDefinition) == false)
playerUnity.objectInHand = null;
}
}
}
}
}
}
}
}
private void UpdateJump()
{
playerUnity.player.input.jump = Input.GetKey(KeyCode.Space);
}
private void UpdateMovement()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 dirWalk = transform.forward * v;
Vector3 dirStrafe = transform.right * h;
Vector3 dir = dirWalk + dirStrafe;
dir.y = 0;
dir.Normalize();
playerUnity.player.input.moveDirection = GraphicsUnity.Vector3ToCubeWorldVector3(dir);
}
private void UpdateCameraRotation()
{
if (Screen.lockCursor)
{
if (axes == RotationAxes.MouseXAndY)
{
// Read the mouse input axis
rotationYaxis += Input.GetAxis("Mouse X") * sensitivityX;
rotationXaxis += Input.GetAxis("Mouse Y") * sensitivityY;
rotationYaxis = ClampAngle(rotationYaxis, minimumX, maximumX);
rotationXaxis = ClampAngle(rotationXaxis, minimumY, maximumY);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationYaxis, Vector3.up);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationXaxis, Vector3.left);
playerUnity.mainCamera.transform.localRotation = originalCameraRotation * yQuaternion;
transform.localRotation = originalPlayerRotation * xQuaternion;
}
else if (axes == RotationAxes.MouseX)
{
rotationYaxis += Input.GetAxis("Mouse X") * sensitivityX;
rotationYaxis = ClampAngle(rotationYaxis, minimumX, maximumX);
Quaternion xQuaternion = Quaternion.AngleAxis(rotationYaxis, Vector3.up);
transform.localRotation = originalPlayerRotation * xQuaternion;
}
else
{
rotationXaxis += Input.GetAxis("Mouse Y") * sensitivityY;
rotationXaxis = ClampAngle(rotationXaxis, minimumY, maximumY);
Quaternion yQuaternion = Quaternion.AngleAxis(rotationXaxis, Vector3.left);
playerUnity.mainCamera.transform.localRotation = originalCameraRotation * yQuaternion;
}
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}

Honestly this is a question best asked here.
However, being that it is unity I'm almost 100% sure that there is a built in controller script for android available to you as an option when you try to create a new project.
It sounds like you are creating something for PC and Android? Unless I am reading that incorrectly.
Either way there is definitely a controller script pre-made in Unity for PC projects and probably for android ones as well.

Related

3D fps Game with gun adding recoil

I wanted to add Guns with recoil to my 3d fps game. It worked but for some reason all the time when i look completely downwards i walk backwards or frontwards. This only happens when the gun is active.
The Gun Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunScript : MonoBehaviour
{
[SerializeField] float Recoil = 500f;
[SerializeField] float TimeTillNextShoot;
[SerializeField] float Range = 100f;
[SerializeField] Transform GunTipposition;
[SerializeField] float recoilRadius = 100f;
public Camera PlayerCamera;
public Rigidbody rbPlayer;
private void Update()
{
Shoot();
}
public void Shoot()
{
if (Input.GetButtonDown("Fire1"))
{
RaycastHit hit;
if(Physics.Raycast(PlayerCamera.transform.position, PlayerCamera.transform.forward, out hit, Range))
{
Debug.Log(hit.transform.name);
Enemy Enemytarget = hit.transform.GetComponent<Enemy>();
if(Enemytarget != null)
{
Enemytarget.TakeDamage(true);
}
}
if (gameObject.CompareTag("ShotGun"))
{
Transform RecoilPosition = GunTipposition.transform;
rbPlayer.AddExplosionForce(Recoil, RecoilPosition.position, recoilRadius);
}
}
}
}
The player Movement:
// Some stupid rigidbody based movement by Dani
using System;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Assignables")]
[Tooltip("this is a reference to the MainCamera object, not the parent of it.")]
public Transform playerCam;
[Tooltip("reference to orientation object, needed for moving forward and not up or something.")]
public Transform orientation;
[Tooltip("LayerMask for ground layer, important because otherwise the collision detection wont know what ground is")]
public LayerMask whatIsGround;
private Rigidbody rb;
[Header("Rotation and look")]
private float xRotation;
[Tooltip("mouse/look sensitivity")]
public float sensitivity = 50f;
private float sensMultiplier = 1.5f;
[Header("Movement")]
[Tooltip("additive force amount. every physics update that forward is pressed, this force (multiplied by 1/tickrate) will be added to the player.")]
public float moveSpeed = 4500;
[Tooltip("maximum local velocity before input is cancelled")]
public float maxSpeed = 20;
[Tooltip("normal countermovement when not crouching.")]
public float counterMovement = 0.175f;
private float threshold = 0.01f;
[Tooltip("the maximum angle the ground can have relative to the players up direction.")]
public float maxSlopeAngle = 35f;
private Vector3 crouchScale = new Vector3(1, 0.5f, 1);
private Vector3 playerScale;
[Tooltip("forward force for when a crouch is started.")]
public float slideForce = 400;
[Tooltip("countermovement when sliding. this doesnt work the same way as normal countermovement.")]
public float slideCounterMovement = 0.2f;
private bool readyToJump = true;
private float jumpCooldown = 0.25f;
[Tooltip("this determines the jump force but is also applied when jumping off of walls, if you decrease it, you may end up being able to walljump and then get back onto the wall leading to infinite height.")]
public float jumpForce = 550f;
float x, y;
bool jumping;
private Vector3 normalVector = Vector3.up;
[Header("Wallrunning")]
private float actualWallRotation;
private float wallRotationVel;
private Vector3 wallNormalVector;
[Tooltip("when wallrunning, an upwards force is constantly applied to negate gravity by about half (at default), increasing this value will lead to more upwards force and decreasing will lead to less upwards force.")]
public float wallRunGravity = 1;
[Tooltip("when a wallrun is started, an upwards force is applied, this describes that force.")]
public float initialForce = 20f;
[Tooltip("float to choose how much force is applied outwards when ending a wallrun. this should always be greater than Jump Force")]
public float escapeForce = 600f;
private float wallRunRotation;
[Tooltip("how much you want to rotate the camera sideways while wallrunning")]
public float wallRunRotateAmount = 10f;
[Tooltip("a bool to check if the player is wallrunning because thats kinda necessary.")]
public bool isWallRunning;
[Tooltip("a bool to determine whether or not to actually allow wallrunning.")]
public bool useWallrunning = true;
[Header("Collisions")]
[Tooltip("a bool to check if the player is on the ground.")]
public bool grounded;
[Tooltip("a bool to check if the player is currently crouching.")]
public bool crouching;
private bool surfing;
private bool cancellingGrounded;
private bool cancellingSurf;
private bool cancellingWall;
private bool onWall;
private bool cancelling;
public static PlayerMovement Instance { get; private set; }
void Awake()
{
Instance = this;
rb = GetComponent<Rigidbody>();
//Create a physic material with no friction to allow for wallrunning and smooth movement not being dependant
//and smooth movement not being dependant on the in-built unity physics engine, apart from collisions.
PhysicMaterial mat = new PhysicMaterial("tempMat");
mat.bounceCombine = PhysicMaterialCombine.Average;
mat.bounciness = 0;
mat.frictionCombine = PhysicMaterialCombine.Minimum;
mat.staticFriction = 0;
mat.dynamicFriction = 0;
gameObject.GetComponent<Collider>().material = mat;
}
void Start()
{
playerScale = transform.localScale;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
readyToJump = true;
wallNormalVector = Vector3.up;
}
private void FixedUpdate()
{
Movement();
}
private void Update()
{
MyInput();
Look();
}
private void LateUpdate()
{
//call the wallrunning Function
WallRunning();
WallRunRotate();
}
private void WallRunRotate()
{
FindWallRunRotation();
float num = 12f;
actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, num * Time.deltaTime);
playerCam.localRotation = Quaternion.Euler(playerCam.rotation.eulerAngles.x, playerCam.rotation.eulerAngles.y, actualWallRotation);
}
/// <summary>
/// Find user input. Should put this in its own class but im lazy
/// </summary>
private void MyInput()
{
x = Input.GetAxisRaw("Horizontal");
y = Input.GetAxisRaw("Vertical");
jumping = Input.GetButton("Jump");
crouching = Input.GetKey(KeyCode.LeftControl);
//Crouching
if (Input.GetKeyDown(KeyCode.LeftControl))
StartCrouch();
if (Input.GetKeyUp(KeyCode.LeftControl))
StopCrouch();
}
private void StartCrouch()
{
transform.localScale = crouchScale;
transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
if (rb.velocity.magnitude > 0.2f && grounded)
{
if (grounded)
{
rb.AddForce(orientation.transform.forward * slideForce);
}
}
}
private void StopCrouch()
{
transform.localScale = playerScale;
transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
}
private void Movement()
{
//Extra gravity
rb.AddForce(Vector3.down * Time.deltaTime * 10);
//Find actual velocity relative to where player is looking
Vector2 mag = FindVelRelativeToLook();
float xMag = mag.x, yMag = mag.y;
//Counteract sliding and sloppy movement
CounterMovement(x, y, mag);
//If holding jump && ready to jump, then jump
if (readyToJump && jumping) Jump();
//Set max speed
float maxSpeed = this.maxSpeed;
//If sliding down a ramp, add force down so player stays grounded and also builds speed
if (crouching && grounded && readyToJump)
{
rb.AddForce(Vector3.down * Time.deltaTime * 3000);
return;
}
//If speed is larger than maxspeed, cancel out the input so you don't go over max speed
if (x > 0 && xMag > maxSpeed) x = 0;
if (x < 0 && xMag < -maxSpeed) x = 0;
if (y > 0 && yMag > maxSpeed) y = 0;
if (y < 0 && yMag < -maxSpeed) y = 0;
//Some multipliers
float multiplier = 1f, multiplierV = 1f;
// Movement in air
if (!grounded)
{
multiplier = 0.5f;
multiplierV = 0.5f;
}
// Movement while sliding
if (grounded && crouching) multiplierV = 0f;
//Apply forces to move player
rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
}
private void Jump()
{
if ((grounded || isWallRunning || surfing) && readyToJump)
{
MonoBehaviour.print("jumping");
Vector3 velocity = rb.velocity;
readyToJump = false;
rb.AddForce(Vector2.up * jumpForce * 1.5f);
rb.AddForce(normalVector * jumpForce * 0.5f);
if (rb.velocity.y < 0.5f)
{
rb.velocity = new Vector3(velocity.x, 0f, velocity.z);
}
else if (rb.velocity.y > 0f)
{
rb.velocity = new Vector3(velocity.x, velocity.y / 2f, velocity.z);
}
if (isWallRunning)
{
rb.AddForce(wallNormalVector * jumpForce * 3f);
}
Invoke("ResetJump", jumpCooldown);
if (isWallRunning)
{
isWallRunning = false;
}
}
}
private void ResetJump()
{
readyToJump = true;
}
private float desiredX;
private void Look()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
//Find current look rotation
Vector3 rot = playerCam.transform.localRotation.eulerAngles;
desiredX = rot.y + mouseX;
//Rotate, and also make sure we dont over- or under-rotate.
xRotation -= mouseY;
float clamp = 89.5f;
xRotation = Mathf.Clamp(xRotation, -clamp, clamp);
//Perform the rotations
playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0);
}
private void CounterMovement(float x, float y, Vector2 mag)
{
if (!grounded || jumping) return;
//Slow down sliding
if (crouching)
{
rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement);
return;
}
//Counter movement
if (Math.Abs(mag.x) > threshold && Math.Abs(x) < 0.05f || (mag.x < -threshold && x > 0) || (mag.x > threshold && x < 0))
{
rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement);
}
if (Math.Abs(mag.y) > threshold && Math.Abs(y) < 0.05f || (mag.y < -threshold && y > 0) || (mag.y > threshold && y < 0))
{
rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement);
}
//Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maxSpeed)
{
float fallspeed = rb.velocity.y;
Vector3 n = rb.velocity.normalized * maxSpeed;
rb.velocity = new Vector3(n.x, fallspeed, n.z);
}
}
/// <summary>
/// Find the velocity relative to where the player is looking
/// Useful for vectors calculations regarding movement and limiting movement
/// </summary>
/// <returns></returns>
public Vector2 FindVelRelativeToLook()
{
float lookAngle = orientation.transform.eulerAngles.y;
float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
float u = Mathf.DeltaAngle(lookAngle, moveAngle);
float v = 90 - u;
float magnitue = rb.velocity.magnitude;
float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
return new Vector2(xMag, yMag);
}
//a lot of math (dont touch)
private void FindWallRunRotation()
{
if (!isWallRunning)
{
wallRunRotation = 0f;
return;
}
_ = new Vector3(0f, playerCam.transform.rotation.y, 0f).normalized;
new Vector3(0f, 0f, 1f);
float num = 0f;
float current = playerCam.transform.rotation.eulerAngles.y;
if (Math.Abs(wallNormalVector.x - 1f) < 0.1f)
{
num = 90f;
}
else if (Math.Abs(wallNormalVector.x - -1f) < 0.1f)
{
num = 270f;
}
else if (Math.Abs(wallNormalVector.z - 1f) < 0.1f)
{
num = 0f;
}
else if (Math.Abs(wallNormalVector.z - -1f) < 0.1f)
{
num = 180f;
}
num = Vector3.SignedAngle(new Vector3(0f, 0f, 1f), wallNormalVector, Vector3.up);
float num2 = Mathf.DeltaAngle(current, num);
wallRunRotation = (0f - num2 / 90f) * wallRunRotateAmount;
if (!useWallrunning)
{
return;
}
if ((Mathf.Abs(wallRunRotation) < 4f && y > 0f && Math.Abs(x) < 0.1f) || (Mathf.Abs(wallRunRotation) > 22f && y < 0f && Math.Abs(x) < 0.1f))
{
if (!cancelling)
{
cancelling = true;
CancelInvoke("CancelWallrun");
Invoke("CancelWallrun", 0.2f);
}
}
else
{
cancelling = false;
CancelInvoke("CancelWallrun");
}
}
private bool IsFloor(Vector3 v)
{
return Vector3.Angle(Vector3.up, v) < maxSlopeAngle;
}
private bool IsSurf(Vector3 v)
{
float num = Vector3.Angle(Vector3.up, v);
if (num < 89f)
{
return num > maxSlopeAngle;
}
return false;
}
private bool IsWall(Vector3 v)
{
return Math.Abs(90f - Vector3.Angle(Vector3.up, v)) < 0.05f;
}
private bool IsRoof(Vector3 v)
{
return v.y == -1f;
}
/// <summary>
/// Handle ground detection
/// </summary>
private void OnCollisionStay(Collision other)
{
int layer = other.gameObject.layer;
if ((int)whatIsGround != ((int)whatIsGround | (1 << layer)))
{
return;
}
for (int i = 0; i < other.contactCount; i++)
{
Vector3 normal = other.contacts[i].normal;
if (IsFloor(normal))
{
if (isWallRunning)
{
isWallRunning = false;
}
grounded = true;
normalVector = normal;
cancellingGrounded = false;
CancelInvoke("StopGrounded");
}
if (IsWall(normal) && (layer == (int)whatIsGround || (int)whatIsGround == -1 || layer == LayerMask.NameToLayer("Ground") || layer == LayerMask.NameToLayer("ground"))) //seriously what is this
{
StartWallRun(normal);
onWall = true;
cancellingWall = false;
CancelInvoke("StopWall");
}
if (IsSurf(normal))
{
surfing = true;
cancellingSurf = false;
CancelInvoke("StopSurf");
}
IsRoof(normal);
}
float num = 3f;
if (!cancellingGrounded)
{
cancellingGrounded = true;
Invoke("StopGrounded", Time.deltaTime * num);
}
if (!cancellingWall)
{
cancellingWall = true;
Invoke("StopWall", Time.deltaTime * num);
}
if (!cancellingSurf)
{
cancellingSurf = true;
Invoke("StopSurf", Time.deltaTime * num);
}
}
private void StopGrounded()
{
grounded = false;
}
private void StopWall()
{
onWall = false;
isWallRunning = false;
}
private void StopSurf()
{
surfing = false;
}
//wallrunning functions
private void CancelWallrun()
{
//for when we want to stop wallrunning
MonoBehaviour.print("cancelled wallrun");
Invoke("GetReadyToWallrun", 0.1f);
rb.AddForce(wallNormalVector * escapeForce);
isWallRunning = false;
}
private void StartWallRun(Vector3 normal)
{
MonoBehaviour.print("wallrunning");
//cancels all y momentum and then applies an upwards force.
if (!grounded && useWallrunning)
{
wallNormalVector = normal;
if (!isWallRunning)
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(Vector3.up * initialForce, ForceMode.Impulse);
}
isWallRunning = true;
}
}
private void WallRunning()
{
//checks if the wallrunning bool is set to true and if it is then applies
//a force to counter gravity enough to make it feel like wallrunning
if (isWallRunning)
{
rb.AddForce(-wallNormalVector * Time.deltaTime * moveSpeed);
rb.AddForce(Vector3.up * Time.deltaTime * rb.mass * 40f * wallRunGravity * -Physics.gravity.y);
}
}
}
I used a addForce funktion to add the recoil.Please help me.
This sentence is juist written because i need to add more details

How can i stop the coroutine immediately in the middle once the player is not looking at any target anymore?

When the player is looking at a target the ui text is enabled true and it's showing some text.
void OnAnimatorIK()
{
if (lookObjs != null)
{
lookObjs.RemoveAll(x => x == null);
InteractableItem primaryTarget = null;
float closestLookWeight = 0;
// Here we find the target which is closest (by angle) to the players view line
allDetectedItems.Clear();
foreach (InteractableItem target in lookObjs)
{
if (target.enabledInteraction == false)
{
continue;
}
Vector3 lookAt = target.transform.position - transform.position;
lookAt.y = 0f;
// Filter out all objects that are too far away
if (lookAt.magnitude > target.distance) continue;
RaycastHit hit;
if (Physics.Raycast(playerEyes.transform.position, target.transform.position - playerEyes.transform.position, out hit, target.distance, ~LayerMask.GetMask("kid_from_space")))
{
if (hit.collider.gameObject == target.gameObject)
{
float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);
float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
if (lookWeight > 0.1f && lookWeight > closestLookWeight)
{
closestLookWeight = lookWeight;
primaryTarget = target;
if (showText && primaryTarget.description != "")
{
StartCoroutine(WaitBeforeShowingText(primaryTarget));
showText = false;
}
}
allDetectedItems.Add(target);
}
else
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
}
}
}
InteractWithTarget(primaryTarget, closestLookWeight);
}
}
This line start the coroutine that showing the text :
StartCoroutine(WaitBeforeShowingText(primaryTarget));
and inside the coroutine
IEnumerator WaitBeforeShowingText(InteractableItem primaryTarget)
{
yield return new WaitForSeconds(1f);
descriptionTextImage.SetActive(true);
text.text = primaryTarget.description;
}
i did it because i wanted to give some delay before showing the text when the player is looking at a target.
the problem is if the coroutine started but before even showing the text i'm rotating the player to NOT looking at any target but because the coroutine started already it will show the text even if the player is not looking anymore at any target.
so the coroutine must be stopped somehow in the middle and show no text.
another possible problem is what if there are two close targets and i move/rotate the player so the target he is looking at will change too fast for the coroutine ?
This is the full code :
using UnityEngine;
using System;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using TMPro;
[RequireComponent(typeof(Animator))]
public class IKControl : MonoBehaviour
{
public List<InteractableItem> lookObjs = new List<InteractableItem>();
public TextMeshProUGUI text;
public float weightDamping = 1.5f;
public bool RightHandToTarget = false;
public GameObject descriptionTextImage;
public float duration;
private List<InteractableItem> allDetectedItems;
private Animator animator;
private InteractableItem lastPrimaryTarget;
private float lerpEndDistance = 0.1f;
private float finalLookWeight = 0;
private bool transitionToNextTarget = false;
private float t;
private bool showText = true;
private GameObject playerEyes;
void Start()
{
playerEyes = GameObject.Find("rig_head");//"rig_eye.L");
animator = GetComponent<Animator>();
allDetectedItems = new List<InteractableItem>();
t = 0;
}
// Callback for calculating IK
void OnAnimatorIK()
{
if (lookObjs != null)
{
lookObjs.RemoveAll(x => x == null);
InteractableItem primaryTarget = null;
float closestLookWeight = 0;
// Here we find the target which is closest (by angle) to the players view line
allDetectedItems.Clear();
foreach (InteractableItem target in lookObjs)
{
if (target.enabledInteraction == false)
{
continue;
}
Vector3 lookAt = target.transform.position - transform.position;
lookAt.y = 0f;
// Filter out all objects that are too far away
if (lookAt.magnitude > target.distance) continue;
RaycastHit hit;
if (Physics.Raycast(playerEyes.transform.position, target.transform.position - playerEyes.transform.position, out hit, target.distance, ~LayerMask.GetMask("kid_from_space")))
{
if (hit.collider.gameObject == target.gameObject)
{
// First object hit was the target so there is a clear line of sight
//Debug.DrawRay(playerEyes.transform.position, Vector3.forward, Color.red);
float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);
float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
if (lookWeight > 0.1f && lookWeight > closestLookWeight)
{
closestLookWeight = lookWeight;
primaryTarget = target;
if (showText && primaryTarget.description != "")
{
StartCoroutine(WaitBeforeShowingText(primaryTarget));
showText = false;
}
}
allDetectedItems.Add(target);
}
else
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
}
}
}
InteractWithTarget(primaryTarget, closestLookWeight);
}
}
private void InteractWithTarget(InteractableItem primaryTarget, float closestLookWeight)
{
if (primaryTarget != null)
{
if ((lastPrimaryTarget != null) && (lastPrimaryTarget != primaryTarget) && (finalLookWeight > 0f))
{
// Here we start a new transition because the player looks already to a target but
// we have found another target the player should look at
transitionToNextTarget = true;
}
}
// The player is in a neutral look position but has found a new target
if ((primaryTarget != null) && !transitionToNextTarget)
{
if (primaryTarget.IsAnyAction())
{
RightHandToTarget = true;
}
lastPrimaryTarget = primaryTarget;
finalLookWeight = Mathf.Lerp(finalLookWeight, 1f, Time.deltaTime * weightDamping);
float bodyWeight = finalLookWeight * .1f;
animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
animator.SetLookAtPosition(primaryTarget.transform.position);
if (RightHandToTarget && primaryTarget.IsAnyAction())
{
Vector3 relativePos = primaryTarget.transform.position - transform.position;
Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
if (primaryTarget.interactableMode == InteractableItem.InteractableMode.ActionWithoutThrow)
{
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 1f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, primaryTarget.transform.position);
}
if (primaryTarget.interactableMode == InteractableItem.InteractableMode.Action)
{
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.1f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, primaryTarget.transform.position);
}
}
}
// Let the player smoothly look away from the last target to the neutral look position
if ((primaryTarget == null && lastPrimaryTarget != null) || transitionToNextTarget)
{
finalLookWeight = Mathf.Lerp(finalLookWeight, 0f, t / duration);//Time.deltaTime * weightDamping);
t += Time.deltaTime;
float bodyWeight = finalLookWeight * .1f;
animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
animator.SetLookAtPosition(lastPrimaryTarget.transform.position);
if (RightHandToTarget)
{
Vector3 relativePos = lastPrimaryTarget.transform.position - transform.position;
Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.5f * closestLookWeight);
animator.SetIKPosition(AvatarIKGoal.RightHand, lastPrimaryTarget.transform.position);
}
if (finalLookWeight < lerpEndDistance)
{
showText = true;
text.text = "";
descriptionTextImage.SetActive(false);
transitionToNextTarget = false;
finalLookWeight = 0f;
lastPrimaryTarget = null;
transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0);
}
}
}
IEnumerator WaitBeforeShowingText(InteractableItem primaryTarget)
{
yield return new WaitForSeconds(1f);
descriptionTextImage.SetActive(true);
text.text = primaryTarget.description;
}
}
To stop a Coroutine, call StopCoroutine(WaitBeforeShowingText);
Here is the doc :
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

Unity MouseLook script will not rotate on the X axis

I am working on a Unity PlayerLook script and as soon as I enable the vertical rotation code I can look vertically, but my side to side motion is locked, with the camera only jittering. Disabling the vertical rotation code allows my camera to look horizontally.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
If you are making an FPS game I was working on one not too long ago and got a solution like, create a new script and put it in the main camera, then in unity drag and drop your player object to the Player Body component on the Main Camera Script that you just created (Keep note that the script name must be named "MouseDir" for it to work):
I don't know why the Mouse X does not work I had the same problem awhile ago.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseDir : MonoBehaviour
{
public Transform playerBody;
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void LateUpdate()
{
transform.position = playerBody.transform.position;
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
playerBody.localEulerAngles = new Vector3(0, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
playerBody.Rotate(0, Input.GetAxis("Mouse X ") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
}
I got the mouselook and movement to work with this script I found online:
https://github.com/TheBozzz34/PR-Terrain-Multiplayer/blob/main/Assets/FirstPersion%20AIO%20Pack/FirstPersonAIO/FirstPersonAIO.cs
private void Update(){
#region Look Settings - Update
if(enableCameraMovement && !controllerPauseState){
float mouseYInput = 0;
float mouseXInput = 0;
float camFOV = playerCamera.fieldOfView;
if (cameraInputMethod == CameraInputMethod.Traditional || cameraInputMethod == CameraInputMethod.TraditionalWithConstraints){
mouseYInput = mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.X ? Input.GetAxis("Mouse Y") : -Input.GetAxis("Mouse Y");
mouseXInput = mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.Y ? Input.GetAxis("Mouse X") : -Input.GetAxis("Mouse X");
}
else{
mouseXInput= Input.GetAxis("Horizontal") * (mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.Y ? 1 : -1);
} if(targetAngles.y > 180) { targetAngles.y -= 360; followAngles.y -= 360; } else if(targetAngles.y < -180) { targetAngles.y += 360; followAngles.y += 360; }
if(targetAngles.x > 180) { targetAngles.x -= 360; followAngles.x -= 360; } else if(targetAngles.x < -180) { targetAngles.x += 360; followAngles.x += 360; }
targetAngles.y += mouseXInput * (mouseSensitivity - ((baseCamFOV-camFOV)*fOVToMouseSensitivity)/6f);
if (cameraInputMethod == CameraInputMethod.Traditional){ targetAngles.x += mouseYInput * (mouseSensitivity - ((baseCamFOV - camFOV) * fOVToMouseSensitivity) / 6f);}
else {targetAngles.x = 0f;}
targetAngles.x = Mathf.Clamp(targetAngles.x, -0.5f * verticalRotationRange, 0.5f * verticalRotationRange);
followAngles = Vector3.SmoothDamp(followAngles, targetAngles, ref followVelocity, (cameraSmoothing)/100);
playerCamera.transform.localRotation = Quaternion.Euler(-followAngles.x + originalRotation.x,0,0);
transform.localRotation = Quaternion.Euler(0, followAngles.y+originalRotation.y, 0);
}
#endregion
#region Input Settings - Update
if(canHoldJump ? (canJump && Input.GetButton("Jump")) : (Input.GetButtonDown("Jump") && canJump) ){
jumpInput = true;
}else if(Input.GetButtonUp("Jump")){jumpInput = false;}
if(_crouchModifiers.useCrouch){
if(!_crouchModifiers.toggleCrouch){ isCrouching = _crouchModifiers.crouchOverride || Input.GetKey(_crouchModifiers.crouchKey);}
else if(Input.GetKeyDown(_crouchModifiers.crouchKey)){isCrouching = !isCrouching || _crouchModifiers.crouchOverride;}
}
if(Input.GetButtonDown("Cancel")){ControllerPause();}
#endregion
#region Movement Settings - Update
#endregion
#region Headbobbing Settings - Update
#endregion
}
private void FixedUpdate(){
#region Look Settings - FixedUpdate
#endregion
#region Movement Settings - FixedUpdate
if(useStamina){
isSprinting = Input.GetKey(sprintKey) && !isCrouching && staminaInternal > 0 && (Mathf.Abs(fps_Rigidbody.velocity.x) > 0.01f || Mathf.Abs(fps_Rigidbody.velocity.z) > 0.01f);
if(isSprinting){
staminaInternal -= (staminaDepletionSpeed*2)*Time.deltaTime;
if(drawStaminaMeter){
StaminaMeterBG.color = Vector4.MoveTowards(StaminaMeterBG.color, new Vector4(0,0,0,0.5f),0.15f);
StaminaMeter.color = Vector4.MoveTowards(StaminaMeter.color, new Vector4(1,1,1,1),0.15f);
}
}else if((!Input.GetKey(sprintKey)||Mathf.Abs(fps_Rigidbody.velocity.x)< 0.01f || Mathf.Abs(fps_Rigidbody.velocity.z)< 0.01f || isCrouching)&&staminaInternal<staminaLevel){
staminaInternal += staminaDepletionSpeed*Time.deltaTime;
}
if(drawStaminaMeter){
if(staminaInternal==staminaLevel){ StaminaMeterBG.color = Vector4.MoveTowards(StaminaMeterBG.color, new Vector4(0,0,0,0),0.15f);
StaminaMeter.color = Vector4.MoveTowards(StaminaMeter.color, new Vector4(1,1,1,0),0.15f);}
float x = Mathf.Clamp(Mathf.SmoothDamp(StaminaMeter.transform.localScale.x,(staminaInternal/staminaLevel)*StaminaMeterBG.transform.localScale.x,ref smoothRef,(1)*Time.deltaTime,1),0.001f, StaminaMeterBG.transform.localScale.x);
StaminaMeter.transform.localScale = new Vector3(x,1,1);
}
staminaInternal = Mathf.Clamp(staminaInternal,0,staminaLevel);
} else{isSprinting = Input.GetKey(sprintKey);}
Vector3 MoveDirection = Vector3.zero;
speed = walkByDefault ? isCrouching ? walkSpeedInternal : (isSprinting ? sprintSpeedInternal : walkSpeedInternal) : (isSprinting ? walkSpeedInternal : sprintSpeedInternal);
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingUpright && advanced.isTouchingWalkable){
MoveDirection = (transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal);
if(!didJump){fps_Rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;}
}
else if(advanced.isTouchingUpright && !advanced.isTouchingWalkable){
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
}
else{
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
MoveDirection = ((transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal) * (fps_Rigidbody.velocity.y>0.01f ? SlopeCheck() : 0.8f));
}
}
else{
MoveDirection = (transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal);
}
#region step logic
RaycastHit WT;
if(advanced.maxStepHeight > 0 && Physics.Raycast(transform.position - new Vector3(0,((capsule.height/2)*transform.localScale.y)-0.01f,0),MoveDirection,out WT,capsule.radius+0.15f,Physics.AllLayers,QueryTriggerInteraction.Ignore) && Vector3.Angle(WT.normal, Vector3.up)>88){
RaycastHit ST;
if(!Physics.Raycast(transform.position - new Vector3(0,((capsule.height/2)*transform.localScale.y)-(advanced.maxStepHeight),0),MoveDirection,out ST,capsule.radius+0.25f,Physics.AllLayers,QueryTriggerInteraction.Ignore)){
advanced.stairMiniHop = true;
transform.position += new Vector3(0,advanced.maxStepHeight*1.2f,0);
}
}
Debug.DrawRay(transform.position, MoveDirection,Color.red,0,false);
#endregion
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
inputXY = new Vector2(horizontalInput, verticalInput);
if(inputXY.magnitude > 1) { inputXY.Normalize(); }
#region Jump
yVelocity = fps_Rigidbody.velocity.y;
if(IsGrounded && jumpInput && jumpPowerInternal > 0 && !didJump){
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingFlat || advanced.isTouchingWalkable){
didJump=true;
jumpInput=false;
yVelocity += fps_Rigidbody.velocity.y<0.01f? jumpPowerInternal : jumpPowerInternal/3;
advanced.isTouchingWalkable = false;
advanced.isTouchingFlat = false;
advanced.isTouchingUpright = false;
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
}
}else{
didJump=true;
jumpInput=false;
yVelocity += jumpPowerInternal;
}
}
if(advanced.maxSlopeAngle>0){
if(!didJump && advanced.lastKnownSlopeAngle>5 && advanced.isTouchingWalkable){
yVelocity *= SlopeCheck()/4;
}
if(advanced.isTouchingUpright && !advanced.isTouchingWalkable && !didJump){
yVelocity += Physics.gravity.y;
}
}
#endregion
if(playerCanMove && !controllerPauseState){
fps_Rigidbody.velocity = MoveDirection+(Vector3.up * yVelocity);
} else{fps_Rigidbody.velocity = Vector3.zero;}
if(inputXY.magnitude > 0 || !IsGrounded) {
capsule.sharedMaterial = advanced.zeroFrictionMaterial;
} else { capsule.sharedMaterial = advanced.highFrictionMaterial; }
fps_Rigidbody.AddForce(Physics.gravity * (advanced.gravityMultiplier - 1));
if(advanced.FOVKickAmount>0){
if(isSprinting && !isCrouching && playerCamera.fieldOfView != (baseCamFOV+(advanced.FOVKickAmount*2)-0.01f)){
if(Mathf.Abs(fps_Rigidbody.velocity.x)> 0.5f || Mathf.Abs(fps_Rigidbody.velocity.z)> 0.5f){
playerCamera.fieldOfView = Mathf.SmoothDamp(playerCamera.fieldOfView,baseCamFOV+(advanced.FOVKickAmount*2),ref advanced.fovRef,advanced.changeTime);
}
}
else if(playerCamera.fieldOfView != baseCamFOV){ playerCamera.fieldOfView = Mathf.SmoothDamp(playerCamera.fieldOfView,baseCamFOV,ref advanced.fovRef,advanced.changeTime*0.5f);}
}
if(_crouchModifiers.useCrouch) {
if(isCrouching) {
capsule.height = Mathf.MoveTowards(capsule.height, _crouchModifiers.colliderHeight/1.5f, 5*Time.deltaTime);
walkSpeedInternal = walkSpeed*_crouchModifiers.crouchWalkSpeedMultiplier;
jumpPowerInternal = jumpPower* _crouchModifiers.crouchJumpPowerMultiplier;
} else {
capsule.height = Mathf.MoveTowards(capsule.height, _crouchModifiers.colliderHeight, 5*Time.deltaTime);
walkSpeedInternal = walkSpeed;
sprintSpeedInternal = sprintSpeed;
jumpPowerInternal = jumpPower;
}
}
#endregion
#region Headbobbing Settings - FixedUpdate
float yPos = 0;
float xPos = 0;
float zTilt = 0;
float xTilt = 0;
float bobSwayFactor = 0;
float bobFactor = 0;
float strideLangthen = 0;
float flatVel = 0;
//calculate headbob freq
if(useHeadbob == true || enableAudioSFX){
Vector3 vel = (fps_Rigidbody.position - previousPosition) / Time.deltaTime;
Vector3 velChange = vel - previousVelocity;
previousPosition = fps_Rigidbody.position;
previousVelocity = vel;
springVelocity -= velChange.y;
springVelocity -= springPosition * springElastic;
springVelocity *= springDampen;
springPosition += springVelocity * Time.deltaTime;
springPosition = Mathf.Clamp(springPosition, -0.3f, 0.3f);
if(Mathf.Abs(springVelocity) < springVelocityThreshold && Mathf.Abs(springPosition) < springPositionThreshold) { springPosition = 0; springVelocity = 0; }
flatVel = new Vector3(vel.x, 0.0f, vel.z).magnitude;
strideLangthen = 1 + (flatVel * ((headbobFrequency*2)/10));
headbobCycle += (flatVel / strideLangthen) * (Time.deltaTime / headbobFrequency);
bobFactor = Mathf.Sin(headbobCycle * Mathf.PI * 2);
bobSwayFactor = Mathf.Sin(Mathf.PI * (2 * headbobCycle + 0.5f));
bobFactor = 1 - (bobFactor * 0.5f + 1);
bobFactor *= bobFactor;
yPos = 0;
xPos = 0;
zTilt = 0;
if(jumpLandIntensity>0 && !advanced.stairMiniHop){xTilt = -springPosition * (jumpLandIntensity*5.5f);}
else if(!advanced.stairMiniHop){xTilt = -springPosition;}
if(IsGrounded){
if(new Vector3(vel.x, 0.0f, vel.z).magnitude < 0.1f) { headbobFade = Mathf.MoveTowards(headbobFade, 0.0f,0.5f); } else { headbobFade = Mathf.MoveTowards(headbobFade, 1.0f, Time.deltaTime); }
float speedHeightFactor = 1 + (flatVel * 0.3f);
xPos = -(headbobSideMovement/10) * headbobFade *bobSwayFactor;
yPos = springPosition * (jumpLandIntensity/10) + bobFactor * (headbobHeight/10) * headbobFade * speedHeightFactor;
zTilt = bobSwayFactor * (headbobSwayAngle/10) * headbobFade;
}
}
//apply headbob position
if(useHeadbob == true){
if(fps_Rigidbody.velocity.magnitude >0.1f){
head.localPosition = Vector3.MoveTowards(head.localPosition, snapHeadjointToCapsul ? (new Vector3(originalLocalPosition.x,(capsule.height/2)*head.localScale.y,originalLocalPosition.z) + new Vector3(xPos, yPos, 0)) : originalLocalPosition + new Vector3(xPos, yPos, 0),0.5f);
}else{
head.localPosition = Vector3.SmoothDamp(head.localPosition, snapHeadjointToCapsul ? (new Vector3(originalLocalPosition.x,(capsule.height/2)*head.localScale.y,originalLocalPosition.z) + new Vector3(xPos, yPos, 0)) : originalLocalPosition + new Vector3(xPos, yPos, 0),ref miscRefVel, 0.15f);
}
head.localRotation = Quaternion.Euler(xTilt, 0, zTilt);
}
#endregion
#region Dynamic Footsteps
if(enableAudioSFX){
if(fsmode == FSMode.Dynamic)
{
RaycastHit hit = new RaycastHit();
if(Physics.Raycast(transform.position, Vector3.down, out hit)){
if(dynamicFootstep.materialMode == DynamicFootStep.matMode.physicMaterial){
dynamicFootstep.currentClipSet = (dynamicFootstep.woodPhysMat.Any() && dynamicFootstep.woodPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.woodClipSet.Any()) ? // If standing on Wood
dynamicFootstep.woodClipSet : ((dynamicFootstep.grassPhysMat.Any() && dynamicFootstep.grassPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.grassClipSet.Any()) ? // If standing on Grass
dynamicFootstep.grassClipSet : ((dynamicFootstep.metalAndGlassPhysMat.Any() && dynamicFootstep.metalAndGlassPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.metalAndGlassClipSet.Any()) ? // If standing on Metal/Glass
dynamicFootstep.metalAndGlassClipSet : ((dynamicFootstep.rockAndConcretePhysMat.Any() && dynamicFootstep.rockAndConcretePhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.rockAndConcreteClipSet.Any()) ? // If standing on Rock/Concrete
dynamicFootstep.rockAndConcreteClipSet : ((dynamicFootstep.dirtAndGravelPhysMat.Any() && dynamicFootstep.dirtAndGravelPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.dirtAndGravelClipSet.Any()) ? // If standing on Dirt/Gravle
dynamicFootstep.dirtAndGravelClipSet : ((dynamicFootstep.mudPhysMat.Any() && dynamicFootstep.mudPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.mudClipSet.Any())? // If standing on Mud
dynamicFootstep.mudClipSet : ((dynamicFootstep.customPhysMat.Any() && dynamicFootstep.customPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.customClipSet.Any())? // If standing on the custom material
dynamicFootstep.customClipSet : footStepSounds)))))); // If material is unknown, fall back
}else if (hit.collider.GetComponent<MeshRenderer>()){
dynamicFootstep.currentClipSet = (dynamicFootstep.woodMat.Any() && dynamicFootstep.woodMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.woodClipSet.Any()) ? // If standing on Wood
dynamicFootstep.woodClipSet : ((dynamicFootstep.grassMat.Any() && dynamicFootstep.grassMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.grassClipSet.Any()) ? // If standing on Grass
dynamicFootstep.grassClipSet : ((dynamicFootstep.metalAndGlassMat.Any() && dynamicFootstep.metalAndGlassMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.metalAndGlassClipSet.Any()) ? // If standing on Metal/Glass
dynamicFootstep.metalAndGlassClipSet : ((dynamicFootstep.rockAndConcreteMat.Any() && dynamicFootstep.rockAndConcreteMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.rockAndConcreteClipSet.Any()) ? // If standing on Rock/Concrete
dynamicFootstep.rockAndConcreteClipSet : ((dynamicFootstep.dirtAndGravelMat.Any() && dynamicFootstep.dirtAndGravelMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.dirtAndGravelClipSet.Any()) ? // If standing on Dirt/Gravle
dynamicFootstep.dirtAndGravelClipSet : ((dynamicFootstep.mudMat.Any() && dynamicFootstep.mudMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.mudClipSet.Any())? // If standing on Mud
dynamicFootstep.mudClipSet : ((dynamicFootstep.customMat.Any() && dynamicFootstep.customMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.customClipSet.Any())? // If standing on the custom material
dynamicFootstep.customClipSet : footStepSounds.Any() ? footStepSounds : null)))))); // If material is unknown, fall back
}
if(IsGrounded)
{
if(!previousGrounded)
{
if(dynamicFootstep.currentClipSet.Any()) { audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
if(dynamicFootstep.currentClipSet.Any()){ audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(dynamicFootstep.currentClipSet.Any()){ audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
}
previousGrounded = false;
}
} else {
dynamicFootstep.currentClipSet = footStepSounds;
if(IsGrounded)
{
if(!previousGrounded)
{
if(landSound){ audioSource.PlayOneShot(landSound,Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
int n = Random.Range(0, footStepSounds.Count);
if(footStepSounds.Any()){ audioSource.PlayOneShot(footStepSounds[n],Volume/10); }
footStepSounds[n] = footStepSounds[0];
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(jumpSound){ audioSource.PlayOneShot(jumpSound,Volume/10); }
}
previousGrounded = false;
}
}
} else
{
if(IsGrounded)
{
if(!previousGrounded)
{
if(landSound) { audioSource.PlayOneShot(landSound,Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
int n = Random.Range(0, footStepSounds.Count);
if(footStepSounds.Any() && footStepSounds[n] != null){ audioSource.PlayOneShot(footStepSounds[n],Volume/10);}
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(jumpSound) { audioSource.PlayOneShot(jumpSound,Volume/10); }
}
previousGrounded = false;
}
}
}
#endregion
#region Reset Checks
IsGrounded = false;
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingFlat || advanced.isTouchingWalkable || advanced.isTouchingUpright){didJump = false;}
advanced.isTouchingWalkable = false;
advanced.isTouchingUpright = false;
advanced.isTouchingFlat = false;
}
#endregion
}

Error in C # script in Unity. ImageEffects

Unity script error. The error occurs after adding the "extreme drift" asset.
Here is the mistake itself
"Assets\Extreme Drift\Scripts\Vehicle\VehicleCamera.cs(5,28): error CS0234: The type or namespace name 'ImageEffects' does not exist in the namespace 'UnityStandardAssets' (are you missing an assembly reference?)"
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityStandardAssets.ImageEffects;
public class VehicleCamera : MonoBehaviour
{
public static VehicleCamera manage;
public float smooth = 0.3f;
public float distance = 5.0f;
public float height = 1.0f;
public float angle = 20;
public LayerMask lineOfSightMask = 0;
[HideInInspector]
public Transform target;
[HideInInspector]
public List<Transform> cameraSwitchView;
private bool farCameraView = false;
private Vector3 farCameraPosition;
private Vector3 velocity = Vector3.zero;
private float Xsmooth;
private float farDistance = 0.0f;
private float zAngleAmount = 0.0f;
private float timeScale = 0.0f;
private float currentDistance;
private int Switch = -1;
void Awake()
{
manage = this;
farCameraPosition = transform.position;
}
void Start()
{
farCameraView = true;
farCameraPosition = (AIControl.manage.firstAINode.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode.position)
+ new Vector3(Random.Range(-5.0f, 5.0f), Random.Range(5.0f, 10.0f), Random.Range(-5.0f, 5.0f));
}
void LateUpdate()
{
if (GameUI.manage.gameFinished)
Switch = 4;
farDistance = Vector3.Distance(farCameraPosition, target.position);
if (farDistance < 100.0f && farCameraView) farCameraView = false;
transform.GetComponent<Blur>().enabled = GameUI.manage.gamePaused ? true : false;
// add MotionBlur effect to camera
if (AIControl.CurrentVehicle.shifting || GameUI.manage.driftAmount > 25)
transform.GetComponent<MotionBlur>().blurAmount = Mathf.Lerp(transform.GetComponent<MotionBlur>().blurAmount, 0.5f, Time.deltaTime * 5);
else
transform.GetComponent<MotionBlur>().blurAmount = Mathf.Lerp(transform.GetComponent<MotionBlur>().blurAmount, 0.0f, Time.deltaTime);
if (Switch == -1)
{
RenderSettings.flareStrength = 0.3f;
GetComponent<Camera>().fieldOfView = Mathf.Clamp(AIControl.CurrentVehicle.speed / 10.0f + 60.0f, 60, 90.0f);
currentDistance = distance;
float yAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y,
target.eulerAngles.y, ref velocity.y, smooth);
float xAngle = Mathf.SmoothDampAngle(transform.eulerAngles.x,
target.eulerAngles.x + (angle), ref velocity.x, smooth);
// Look at the target
transform.eulerAngles = new Vector3(xAngle, yAngle, AccelerationAngle());
Xsmooth = Mathf.Lerp(Xsmooth, velocity.y, Time.deltaTime * 10.0f);
var direction = transform.rotation * -new Vector3(-Xsmooth / 300.0f, 0, 1);
var targetDistance = AdjustLineOfSight(target.position + new Vector3(0, height, 0), direction);
transform.position = target.position + new Vector3(0, height, 0) + direction * targetDistance;
}
else if (Switch < AIControl.CurrentVehicle.cameraView.cameraSwitchView.Count)
{
RenderSettings.flareStrength = 0.3f;
GetComponent<Camera>().fieldOfView = 60;
transform.position = cameraSwitchView[Switch].position;
transform.rotation = Quaternion.Lerp(transform.rotation, cameraSwitchView[Switch].rotation, Time.deltaTime * 5.0f);
}
else {
if (farDistance > 120.0f && !farCameraView)
{
farCameraPosition = (AIControl.CurrentVehicle.AIVehicle.nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode
.GetComponent<AINode>().nextNode.position)
+ new Vector3(Random.Range(-5.0f, 5.0f), Random.Range(10.0f, 15.0f), Random.Range(-5.0f, 5.0f));
farCameraView = true;
}
RenderSettings.flareStrength = 0.0f;
GetComponent<Camera>().fieldOfView = Mathf.Clamp(50.0f - (farDistance / 2.0f), 10.0f, 120.0f);
var newRotation = Quaternion.LookRotation(target.position - transform.position);
transform.position = farCameraPosition;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 15);
}
}
public void CameraSwitch()
{
Switch++;
if (Switch > AIControl.CurrentVehicle.cameraView.cameraSwitchView.Count) { Switch = -1; }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private float AccelerationAngle()
{
zAngleAmount = Mathf.Clamp(zAngleAmount, -45.0f, 45.0f);
zAngleAmount = Mathf.Lerp(zAngleAmount, Input.acceleration.x * -70.0f, Time.deltaTime * 2.0f);
return zAngleAmount;
}
float AdjustLineOfSight(Vector3 target, Vector3 direction)
{
RaycastHit hit;
if (Physics.Raycast(target, direction, out hit, currentDistance, lineOfSightMask.value))
return hit.distance;
else
return currentDistance;
}
}
As I understand it, you need to connect the "Standard assets" to the project, I connected it, but it still does not work.

How can i move the player randomly between the waypoints?

What i'm trying to do is once the random flag is true move the player between the waypoints randomly.
but just calling the random method is not enough.
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Waypoints : MonoBehaviour
{
public GameObject[] waypoints;
public Transform target;
public float moveSpeed = 10f;
public float slowDownSpeed = 3f;
public float reverseSlowDownSpeed = 3f;
public float rotationSpeed = 1f;
private int targetsIndex = 0;
private Vector3 originalPosition;
private GameObject[] players;
public Transform reverseTarget;
private int reverseTargetsIndex = 0;
private Vector3 reverseOriginalPosition;
public bool random = false;
// Use this for initialization
void Start()
{
waypoints = GameObject.FindGameObjectsWithTag("Blocks");
players = GameObject.FindGameObjectsWithTag("Player");
originalPosition = players[0].transform.localPosition;
}
// Update is called once per frame
void Update()
{
if (random == true)
{
RandomWayPointsAI();
}
else
{
WayPointsAI();
}
}
private void WayPointsAI()
{
if (targetsIndex == waypoints.Length)
targetsIndex = 0;
target = waypoints[targetsIndex].transform;
float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
players[0].transform.localPosition += players[0].transform.forward * slowDownSpeed * Time.deltaTime;
}
else
{
players[0].transform.localPosition += players[0].transform.forward * moveSpeed * Time.deltaTime;
}
if (distance < target.transform.localScale.magnitude)
{
targetsIndex++;
}
}
private void ReverseWayPointsAI()
{
if (reverseTargetsIndex == 0)
reverseTargetsIndex = waypoints.Length - 1;
reverseTarget = waypoints[reverseTargetsIndex].transform;
float distance = Vector3.Distance(players[1].transform.position, reverseTarget.transform.position);
players[1].transform.rotation = Quaternion.Slerp(players[1].transform.rotation, Quaternion.LookRotation(reverseTarget.position - players[1].transform.position), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
players[1].transform.position += players[1].transform.forward * reverseSlowDownSpeed * Time.deltaTime;
}
else
{
players[1].transform.position += players[1].transform.forward * moveSpeed * Time.deltaTime;
}
if (distance < reverseTarget.transform.localScale.magnitude)
{
reverseTargetsIndex--;
}
}
void RandomWayPointsAI()
{
if (random == true)
{
int index = UnityEngine.Random.Range(0, waypoints.Length);
target = waypoints[index].transform;
}
}
void DrawLinesInScene()
{
// draw lines between each checkpoint //
for (int i = 0; i < waypoints.Length - 1; i++)
{
Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);
}
// draw a line between the original transform start position
// and the current transform position //
Debug.DrawLine(originalPosition, players[0].transform.position, Color.red);
Debug.DrawLine(reverseOriginalPosition, players[1].transform.position, Color.red);
// draw a line between current transform position and the next waypoint target
// each time reached a waypoint.
if (target != null)
Debug.DrawLine(target.transform.position, players[0].transform.position, Color.green);
if (reverseTarget != null)
Debug.DrawLine(reverseTarget.transform.position, players[1].transform.position, Color.green);
}
void AddColliderToWaypoints()
{
foreach (GameObject go in waypoints)
{
SphereCollider sc = go.AddComponent<SphereCollider>() as SphereCollider;
sc.isTrigger = true;
}
}
}
Inside the Update i'm checking if random is true then calling the RandomWayPointsAI(); but it's not moving the player it's just keep picking up each frame a new random waypoint but that's it.
void Update()
{
if (random == true)
{
RandomWayPointsAI();
}
else
{
WayPointsAI();
}
}
Here is your answer. First you are not writing the movement code in the random function and you are expecting it to move.
bool getNextRandom = true;
void RandomWayPointsAI()
{
if (random == true && getNextRandom)
{
int index = UnityEngine.Random.Range(0, waypoints.Length);
target = waypoints[index].transform;
getNextRandom = false;
}
float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
players[0].transform.localPosition += players[0].transform.forward * slowDownSpeed * Time.deltaTime;
}
else
{
players[0].transform.localPosition += players[0].transform.forward * moveSpeed * Time.deltaTime;
}
if (distance < target.transform.localScale.magnitude)
{
getNextRandom = true;
}
}
Further you can imporve the solution by moving the movement code to another function which will give you better control
public GameObject[] waypoints;
public Transform target;
public float moveSpeed = 10f;
public float slowDownSpeed = 3f;
public float reverseSlowDownSpeed = 3f;
public float rotationSpeed = 1f;
private int targetsIndex = 0;
private Vector3 originalPosition;
private GameObject[] players;
public Transform reverseTarget;
private int reverseTargetsIndex = 0;
private Vector3 reverseOriginalPosition;
public bool random = false;
public bool getNextRandom = true;
// Use this for initialization
void Start()
{
waypoints = GameObject.FindGameObjectsWithTag("Blocks");
players = GameObject.FindGameObjectsWithTag("Player");
originalPosition = players[0].transform.localPosition;
}
// Update is called once per frame
void Update()
{
if (random == true)
{
RandomWayPointsAI();
}
else
{
WayPointsAI();
}
}
private void WayPointsAI()
{
if (targetsIndex == waypoints.Length)
targetsIndex = 0;
target = waypoints[targetsIndex].transform;
if (MovePlayer())
targetsIndex++;
}
private void ReverseWayPointsAI()
{
if (reverseTargetsIndex == 0)
reverseTargetsIndex = waypoints.Length - 1;
reverseTarget = waypoints[reverseTargetsIndex].transform;
if (MovePlayer())
reverseTargetsIndex--;
}
void RandomWayPointsAI()
{
if (random == true && getNextRandom)
{
int index = UnityEngine.Random.Range(0, waypoints.Length);
target = waypoints[index].transform;
getNextRandom = false;
}
getNextRandom = MovePlayer();
}
bool MovePlayer()
{
float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);
//move towards the player
if (distance < 30)
{
players[0].transform.localPosition += players[0].transform.forward * slowDownSpeed * Time.deltaTime;
}
else
{
players[0].transform.localPosition += players[0].transform.forward * moveSpeed * Time.deltaTime;
}
if (distance < target.transform.localScale.magnitude)
return true;
else
return false;
}
void DrawLinesInScene()
{
// draw lines between each checkpoint //
for (int i = 0; i < waypoints.Length - 1; i++)
{
Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);
}
// draw a line between the original transform start position
// and the current transform position //
Debug.DrawLine(originalPosition, players[0].transform.position, Color.red);
Debug.DrawLine(reverseOriginalPosition, players[1].transform.position, Color.red);
// draw a line between current transform position and the next waypoint target
// each time reached a waypoint.
if (target != null)
Debug.DrawLine(target.transform.position, players[0].transform.position, Color.green);
if (reverseTarget != null)
Debug.DrawLine(reverseTarget.transform.position, players[1].transform.position, Color.green);
}
void AddColliderToWaypoints()
{
foreach (GameObject go in waypoints)
{
SphereCollider sc = go.AddComponent<SphereCollider>() as SphereCollider;
sc.isTrigger = true;
}
}
If you look at your RandomWayPointsAI() function, it only defines the index and the target but don't have any code below it to move the player.
private void WayPointsAI()
{
if (targetsIndex == waypoints.Length)
targetsIndex = 0;
target = waypoints[targetsIndex].transform;
float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);
void RandomWayPointsAI()
{
//No need to check if random is true anymore, you already checked when you run this function
int index = UnityEngine.Random.Range(0, waypoints.Length);
target = waypoints[index].transform;
//float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
//players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);**
}

Categories