I am writing a C# script on Unity 3D.
I'm working on pathfinding now.
The path has been found correctly in the Array List and the Object can move according to the path with a constant speed.
Then, I want to improvise, where when the path found is a straight line, the object will increase its speed. Meanwhile, when the path turns the object will reduce its speed again.
Here, I don't know how to group between straight and turning paths in an arrayList.
Thankyou for helping me :)
This is the code :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public abstract class Unit : MonoBehaviour
{
#region public variables
public GameObject Astar;
public bool drawGizmos = false;
protected float gravity = 9.8f;
public Transform target;
public Transform NPC;
public Vector3 lastTargetPosition;
public float movementSpeed;
public float rotationSpeed = 85;
protected float distanceToPath = 1;
public Vector2 currentPosition = new Vector2(0, 0);
protected int spacesMoved = 0;
// Default action times to 5 second interval
protected float period = 1f;
protected float nextActionTime = 1f;
protected bool isSafeToUpdatePath = false;
protected int pathFoundCount = 0;
protected bool isMoving = false;
protected bool isTargetReached = false;
#endregion
#region member variables
public Vector3[] m_path;
protected int m_targetIndex;
protected CharacterController m_characterController;
private Node lastNodePosition;
private List<Node> lastPositionNeighbors;
private Vector3 m_lastKnownPosition;
private Quaternion m_lookAtRotation;
private GridSystem m_grid;
private Coroutine lastRoutine = null;
private bool preventExtraNodeUpdate = false;
public Stopwatch timer;
#endregion
public virtual void Awake()
{
timer = new Stopwatch();
if (Astar != null)
m_grid = Astar.GetComponent<GridSystem>();
}
public virtual void Start()
{
m_characterController = GetComponent<CharacterController>();
timer.Reset();
timer.Start();
PathRequestManager.RequestPath(transform.position, target.position, OnPathFound);
lastTargetPosition = target.position;
UnityEngine.Debug.Log("NPC Position : " + transform.position);
UnityEngine.Debug.Log("Target Position : " + target.position);
}
public virtual void Update()
{
if (Time.time > nextActionTime) //update path setiap 1f
{
nextActionTime += period;
isSafeToUpdatePath = true;
}
else
{
isSafeToUpdatePath = false;
}
//If we don't check !isMoving the AI may get stuck waiting to update the grid for nextActionTime.
if (target.position != lastTargetPosition)
{
isMoving = true;
UpdateNodePosition();
UpdatePath();
UpdateRotation();
}
lastTargetPosition = target.position;
}
public void UpdatePath()
{
lastNodePosition.walkable = Walkable.Passable;
PathRequestManager.RequestPath(transform.position, target.position, OnPathFound);
}
public virtual void OnPathFound(Vector3[] newPath, bool pathSuccessful)
{
if (pathSuccessful)
{
pathFoundCount++;
m_path = newPath;
m_targetIndex = 0;
// Stop coroutine if it is already running.
if (lastRoutine != null)
StopCoroutine(lastRoutine);
lastRoutine = StartCoroutine(FollowPath());
}
}
public float time;
public virtual IEnumerator FollowPath()
{
Vector3 currentPath = m_path[0];
while (true)
{
if (Vector3.Distance(transform.position, currentPath) < distanceToPath)
{
m_targetIndex++;
// If we are done with path.
if (m_targetIndex >= m_path.Length)
{
timer.Stop();
UnityEngine.Debug.Log("Time Move : " + timer.ElapsedMilliseconds);
isMoving = false;
yield break;
}
currentPath = m_path[m_targetIndex];
}
float Distance = Vector3.Distance(NPC.transform.position, target.transform.position);
UnityEngine.Debug.Log("Distance : " + Distance);
// Occurs each frame
//move follow path
UpdatePosition(currentPath);
yield return null;
}
}
public virtual void UpdatePosition(Vector3 destination)
{
Node node = m_grid.NodeFromWorldPoint(transform.position);
Vector3 direction = destination - transform.position;
movementSpeed = 1;
transform.Translate(direction.normalized * movementSpeed * Time.deltaTime, Space.World);
UnityEngine.Debug.Log("Speed NPC : " + movementSpeed);
}
public virtual void UpdateRotation()
{
m_lastKnownPosition = target.transform.position;
m_lookAtRotation = Quaternion.LookRotation(m_lastKnownPosition - transform.position);
if (transform.rotation != m_lookAtRotation)
transform.rotation = Quaternion.RotateTowards(transform.rotation, m_lookAtRotation, rotationSpeed * Time.deltaTime);
}
public void UpdateNodePosition()
{
Node node = m_grid.NodeFromWorldPoint(transform.position);
if (isMoving == false)
{
lastPositionNeighbors = m_grid.GetNeighbours(node);
foreach (Node n in lastPositionNeighbors)
{
if (n.walkable != Walkable.Impassable)
n.walkable = Walkable.Blocked;
}
node.walkable = Walkable.Blocked;
lastNodePosition = node;
currentPosition = new Vector2(node.gridX, node.gridY);
return;
}
if (lastNodePosition != null && isMoving)
{
preventExtraNodeUpdate = false;
lastPositionNeighbors = m_grid.GetNeighbours(node);
lastNodePosition.walkable = Walkable.Passable;
if (lastPositionNeighbors != null)
foreach (Node n in lastPositionNeighbors)
{
if (n.walkable != Walkable.Impassable)
n.walkable = Walkable.Passable;
}
if (!node.Equals(lastNodePosition))
spacesMoved++;
}
else
{
node.walkable = Walkable.Blocked;
lastNodePosition = node;
currentPosition = new Vector2(node.gridX, node.gridY);
}
}
public void OnDrawGizmos()
{
if (!drawGizmos)
return;
if (m_path != null)
{
for (int i = m_targetIndex; i < m_path.Length; i++)
{
Gizmos.color = Color.black;
Gizmos.DrawCube(m_path[i], Vector3.one);
}
}
}
}
This screenshot after running
Okay. It looks to me like all that you have to do in order to determine if you are on a curved path is to check if the next step you are going to take is directly in front of the player. You can do this in your UpdatePosition function. Just check if the direction you are about to move in has the same x or z position. Assuming that y is up and all points on your grid have the same y position. In the case that you are moving horizontally, x will stay the same, and in the case that you are moving vertically, z will stay the same. Or vice versa.
public virtual void UpdatePosition(Vector3 destination)
{
Node node = m_grid.NodeFromWorldPoint(transform.position);
Vector3 direction = destination - transform.position;
if(destination.x == transform.position.x || destination.z == transform.position.z)
{
//Direction is staying the same
movementSpeed = 1f;
}else{
movementSpeed = 0.5f;
}
transform.Translate(direction.normalized * movementSpeed * Time.deltaTime, Space.World);
UnityEngine.Debug.Log("Speed NPC : " + movementSpeed);
}
You should be able to customize the movement speed however you want from there. IF you're having issues still after this, try printing out the (x,y,z) components of the destination and the transform and see where they are similar when the path is straight and what changes when the path is curved. The code above assumes the y never changes.
Related
I am trying to move a GameObject along a path by stages. Conceptually a first script, connected to the controller, defines the path via a List of Vector3 and a second one connected to the object moves it. To move it first rotates to face the destination and then it simply moves by incrementing transform.position by small steps.
The problem is that once the first part of the path has been completed the rest seems to cancel out (the Count became 0) and the robot stops.
This only happens by giving the list from a second script, trying it with a pre-defined list in the same script works fine.
This is the motion code:
public List<Vector3> pathRover;
[SerializeField] private float roverSpeed;
[SerializeField] private float roverRotateSpeed;
private float dotto;
private bool isRotating = false;
private bool isLerping = false;
private Vector3 startPosition;
private Vector3 targetPosition;
private void FixedUpdate()
{
if (isRotating)
{
//To determine whether the robot faces the direction of movement
dotto = Vector3.Dot(transform.TransformDirection(Vector3.forward), (new Vector3(targetPosition.x, 0, targetPosition.z) - new Vector3(startPosition.x, 0, startPosition.z)).normalized);
if (dotto < 0.98f) // rotate until reached then move
{
transform.Rotate(0, Time.deltaTime * roverRotateSpeed, 0);
Debug.Log(dotto);
}
else
{
isLerping = true;
isRotating = false;
}
}
else if (isLerping)
{
var step = roverSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
if (Vector3.Distance(transform.position, targetPosition) <= 1f)
{
NextStep();
}
}
}
public void StartMoving(List<Vector3> pathReceived)
{
if (pathReceived.Count > 1)
{
pathRover.Clear();
for (int i = 1; i < pathReceived.Count; i++)
{
pathRover.Add(pathReceived[i]);
}
startPosition = transform.position;
targetPosition = new Vector3(pathRover[0].x, pathRover[0].y + 0.7f, pathRover[0].z); //0.7f for the height of the rover from the ground
isRotating = true;
}
else
{
StopMoving();
}
}
public void StopMoving()
{
isRotating = false;
isLerping = false;
pathRover.Clear();
}
public void NextStep()
{
isLerping = false;
StartMoving(pathRover);
}
From the other script:
roverMover.StartMoving(percorsoList);
No error appears in the debug console, I don't know where I am wrong.
I guess the problem is you are starting the move right at the Start of the script but you call StartMoving after a while. You have to move only when StartMove is called.
public List<Vector3> pathRover;
[SerializeField] private float roverSpeed;
[SerializeField] private float roverRotateSpeed;
private float dotto;
private bool isRotating = false;
private bool isLerping = false;
private Vector3 startPosition;
private Vector3 targetPosition;
boolean startMove = false;
private void FixedUpdate()
{
if(startMove)
Move();
}
public void Move(){
if (isRotating)
{
//To determine whether the robot faces the direction of movement
dotto = Vector3.Dot(transform.TransformDirection(Vector3.forward), (new Vector3(targetPosition.x, 0, targetPosition.z) - new Vector3(startPosition.x, 0, startPosition.z)).normalized);
if (dotto < 0.98f) // rotate until reached then move
{
transform.Rotate(0, Time.deltaTime * roverRotateSpeed, 0);
Debug.Log(dotto);
}
else
{
isLerping = true;
isRotating = false;
}
}
else if (isLerping)
{
var step = roverSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
if (Vector3.Distance(transform.position, targetPosition) <= 1f)
{
NextStep();
}
}
}
public void StartMoving(List<Vector3> pathReceived)
{
startMove= true;
if (pathReceived.Count > 1)
{
pathRover.Clear();
for (int i = 1; i < pathReceived.Count; i++)
{
pathRover.Add(pathReceived[i]);
}
startPosition = transform.position;
targetPosition = new Vector3(pathRover[0].x, pathRover[0].y + 0.7f, pathRover[0].z); //0.7f for the height of the rover from the ground
isRotating = true;
}
else
{
StopMoving();
}
}
public void StopMoving()
{
isRotating = false;
isLerping = false;
pathRover.Clear();
}
public void NextStep()
{
isLerping = false;
StartMoving(pathRover);
}
So decided to give game dev a try, picked up unity,Now I decided to create a simple ping pong game.
My game has Bat.cs class, ball.cs, and GameHandler.cs.
The GameHandler.cs initializes the batRight, batLeft, ball using the Bat.cs, Ball.cs class and prefabs, it also keeps track of if someone scores then starts a serve by stopping the rally:
public class GameHandler : MonoBehaviour
{
public Bat bat;
public Ball ball;
public Score score;
public static Vector2 bottomLeft;
public static Vector2 topRight;
public static bool rallyOn = false;
public static bool isServingLeft = true;
public static bool isServingRight = false;
public static bool isTwoPlayers = true;
static Bat batRight;
static Bat batLeft;
public static Ball ball1;
static Score scoreLeft;
static Score scoreRight;
// Start is called before the first frame update
void Start()
{
//Convert screens pixels coordinate into games coordinate
bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2(0, 0));
topRight = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
ball1 = Instantiate(ball) as Ball;
//Debug.Log("GameHandler.Start");
batRight = Instantiate(bat) as Bat;
batRight.Init(true);
batLeft = Instantiate(bat) as Bat;
batLeft.Init(false);
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
//Instatiate scores
scoreLeft = Instantiate(score, new Vector2(-2, -4), Quaternion.identity) as Score;
scoreRight = Instantiate(score, new Vector2(2, -4), Quaternion.identity) as Score;
}
private void Update()
{
if (isServingLeft)
{
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
if (Input.GetKey(KeyCode.LeftControl))
{
rallyOn = true;
isServingLeft = false;
}
}
if (isServingRight)
{
ball1.transform.position = new Vector3(batRight.transform.position.x - ball1.getRadius() * 2, batRight.transform.position.y);
if (isTwoPlayers && Input.GetKey(KeyCode.RightControl))
{
rallyOn = true;
isServingRight = false;
}
else
{
StartCoroutine(batRight.serveAi());
if (GameHandler.rallyOn)
{
StopCoroutine(batRight.serveAi());
}
}
}
}
public static void increaseScoreByOne(bool isRight)
{
rallyOn = false;
if (isRight)
{
scoreRight.increaseScore();
isServingRight = true;
}
else
{
scoreLeft.increaseScore();
isServingLeft = true;
}
}
}
The ball.cs listens to the static GameHandler.rallyOn and starts moving the ball accordingly, it also changes direction of the ball if it hits a vertical wall or the bat:
public class Ball : MonoBehaviour
{
[SerializeField]
float speed;
float radius;
public Vector2 direction;
public Vector3 ballPosition;
// Start is called before the first frame update
void Start()
{
direction = Vector2.one.normalized; // direction is (1, 1) normalized
//Debug.Log("direction * speed * Time.deltaTime:" + direction * speed * Time.deltaTime);
radius = transform.localScale.x / 2;
}
// Update is called once per frame
void Update()
{
ballPosition = transform.position;
if (GameHandler.rallyOn)
{
startRally();
}
}
void startRally()
{
transform.Translate(direction * speed * Time.deltaTime);
Debug.Log("direction * speed * Time.deltaTime:" + direction * speed * Time.deltaTime);
if ((transform.position.y + radius) > GameHandler.topRight.y && direction.y > 0)
{
direction.y = -direction.y;
}
if ((transform.position.y + radius) < GameHandler.bottomLeft.y && direction.y < 0)
{
direction.y = -direction.y;
}
if ((transform.position.x + radius) > GameHandler.topRight.x && direction.x > 0)
{
// Left player scores
GameHandler.increaseScoreByOne(false);
//For no, just freeza the script
// Time.timeScale = 0;
//enabled = false;
}
if ((transform.position.x - radius) < GameHandler.bottomLeft.x && direction.x < 0)
{
// right player scores
GameHandler.increaseScoreByOne(true);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Bat")
{
if (collision.GetComponent<Bat>().isRight && direction.x > 0)
{
direction.x = -direction.x;
}
if (!collision.GetComponent<Bat>().isRight && direction.x < 0)
{
direction.x = -direction.x;
}
}
}
public float getRadius()
{
return radius;
}
}
The bat.cs initiazes the two paddles, and either listens to user input if its 2 players or listens to player and use AI if it is player vs CPU.:
public class Bat : MonoBehaviour
{
float height;
[SerializeField] // this make this appear on editor without making this field public
float speed;
string input;
public bool isRight;
string PLAYER1_INPUT = "PaddleLeft";
string PLAYER2_INPUT = "PaddleRight";
// Start is called before the first frame update
void Start()
{
height = transform.localScale.y;
}
// Update is called once per frame
void Update()
{
if (GameHandler.isTwoPlayers)
{
if (isRight)
{
movePaddleonUserInput(PLAYER2_INPUT);
}
else
{
movePaddleonUserInput(PLAYER1_INPUT);
}
}
else
{
if (isRight)
{
movePaddleAi();
}
else
{
movePaddleonUserInput(PLAYER1_INPUT);
}
}
}
void movePaddleAi()
{
if (isRight && GameHandler.ball1.direction.x > 0 && GameHandler.ball1.ballPosition.x > 0)
{
//transform.Translate(direction * speed * Time.deltaTime);
if ((transform.position.y) > GameHandler.ball1.ballPosition.y && GameHandler.ball1.direction.y < 0)
{
transform.Translate(GameHandler.ball1.direction * speed * Time.deltaTime * Vector2.up);
}
if ((transform.position.y) < GameHandler.ball1.ballPosition.y && GameHandler.ball1.direction.y > 0)
{
transform.Translate(GameHandler.ball1.direction * speed * Time.deltaTime * Vector2.up);
}
}
}
void movePaddleonUserInput(string input)
{
// move = (-1 -> 1) * speed * timeDelta(this keep move framerate independent)
float move = Input.GetAxis(input) * speed * Time.deltaTime;
//Debug.Log((transform.position.y + height / 2) + " > "+ GameHandler.topRight.y+ "&&" + move +" > 0");
//Restrict paddle movement to to the screen
// (top edge of paddle > Screen top and we are moving up)
if ((transform.position.y + height / 2) > GameHandler.topRight.y && move > 0)
{
move = 0;
}
// (bottom edge of paddle < Screen top and we are moving down)
if ((transform.position.y - height / 2) < GameHandler.bottomLeft.y && move < 0)
{
move = 0;
}
transform.Translate(move * Vector2.up);
}
public void Init(bool isRightPaddle)
{
isRight = isRightPaddle;
Vector2 pos;
if (isRightPaddle)
{
isRight = isRightPaddle;
pos = new Vector2(GameHandler.topRight.x, 0);
// offset since center is the anchor
pos -= Vector2.right * transform.localScale.x;
input = "PaddleRight";
}
else
{
pos = new Vector2(GameHandler.bottomLeft.x, 0);
// offset since center is the anchor
pos += Vector2.right * transform.localScale.x;
input = "PaddleLeft";
}
transform.name = input;
transform.position = pos;
}
public IEnumerator serveAi()
{
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
GameHandler.isServingRight = false;
}
}
Now I also have score.cs and mainMenu scene , but no need to include that for this question, What I am struggling with now is the AI not stopping after it scores a point, I want the AI paddle to stop for a few seconds before it serves.
As you can see in the code, I added a yield return new WaitForSecondsRealtime(2f);
public IEnumerator serveAi()
{
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
GameHandler.isServingRight = false;
}
But this only cause the paddle to wait for the first time it scores , and then if it scores again in quick interval, it doesn't wait at all.
Not sure what I doing wrong here, thanks for your time.
The more plausible explanation to me would be that GameHandler.rallyOn and isServing* aren't all being reset to the correct values to prevent the serve from occurring before the coroutine even begins, or another check is needed somewhere to prevent a serve from occurring if all of the correct booleans aren't set. Try placing appropriate breakpoints and stepping through in a debugger.
You'd probably be better off using WaitForSeconds rather than WaitForSecondsRealtime, by the way, at least if there's a chance you might want to allow the game to be paused in the future.
Realized that the coroutine is called multiple times even before its finished due do it being called from update function in GameHandler.cs. Needed a way to check if the co-routine is already running and not start a new one from update if so, used the Game.isServing variable to do so:
public IEnumerator serveAi()
{
GameHandler.isServingRight = false; // coroutine started , no need to start new one
yield return new WaitForSecondsRealtime (2f);
GameHandler.rallyOn = true;
}
And my update in GameHandler is already checking for that variable before starting the coroutine:
private void Update()
{
if (isServingLeft)
{
ball1.transform.position = new Vector3(batLeft.transform.position.x + ball1.getRadius() * 2, batLeft.transform.position.y);
if (Input.GetKey(KeyCode.LeftControl))
{
rallyOn = true;
isServingLeft = false;
}
}
if (isServingRight)
{
ball1.transform.position = new Vector3(batRight.transform.position.x - ball1.getRadius() * 2, batRight.transform.position.y);
if (isTwoPlayers && Input.GetKey(KeyCode.RightControl))
{
rallyOn = true;
isServingRight = false;
}
else
{
StartCoroutine(batRight.serveAi());
}
}
}
CurrentlyGrounded Should flip to true and false. Instead, visual studio is reporting that it "Doesn't exist in the current context". How do I force this variable to exist EVERYWHERE in the script?
Making it public did absolutely nothing.
The problem occurs in the private void GroundCheck() method on Line 267.
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (Rigidbody))]
[RequireComponent(typeof (CapsuleCollider))]
public class RigidbodyFirstPersonController : MonoBehaviour
{
[Serializable]
public class MovementSettings
{
public float ForwardSpeed = 8.0f; // Speed when walking forward
public float BackwardSpeed = 4.0f; // Speed when walking backwards
public float StrafeSpeed = 4.0f; // Speed when walking sideways
public float AirForwardSpeed = 8.0f; // Speed when flying forward
public float AirBackwardSpeed = 4.0f; // Speed when flying backwards
public float AirStrafeSpeed = 4.0f; // Speed when flying sideways
public bool CurrentlyGrounded = true;
public float RunMultiplier = 2.0f; // Speed when sprinting
public KeyCode RunKey = KeyCode.LeftShift;
public float JumpForce = 30f;
public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
[HideInInspector] public float CurrentTargetSpeed = 8f;
#if !MOBILE_INPUT
private bool m_Running;
#endif
public void UpdateDesiredTargetSpeed(Vector2 input)
{
if (input == Vector2.zero) return;
if (input.x > 0 || input.x < 0 && CurrentlyGrounded == true)
{
//strafe
CurrentTargetSpeed = StrafeSpeed;
}
else if (input.x > 0 || input.x < 0 && CurrentlyGrounded == false)
{
//strafe
CurrentTargetSpeed = AirStrafeSpeed;
}
if (input.y < 0 && CurrentlyGrounded == true)
{
//backwards
CurrentTargetSpeed = BackwardSpeed;
}
else if (input.y < 0 && CurrentlyGrounded == false)
{
//backwards
CurrentTargetSpeed = AirBackwardSpeed;
}
if (input.y > 0 && CurrentlyGrounded == true)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = ForwardSpeed;
}
else if (input.y > 0 && CurrentlyGrounded == false)
{
//forwards
//handled last as if strafing and moving forward at the same time forwards speed should take precedence
CurrentTargetSpeed = AirForwardSpeed;
}
#if !MOBILE_INPUT
if (Input.GetKey(RunKey))
{
CurrentTargetSpeed *= RunMultiplier;
m_Running = true;
}
else
{
m_Running = false;
}
#endif
}
#if !MOBILE_INPUT
public bool Running
{
get { return m_Running; }
}
#endif
}
[Serializable]
public class AdvancedSettings
{
public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
public float stickToGroundHelperDistance = 0.5f; // stops the character
public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
public bool airControl; // can the user control the direction that is being moved in the air
[Tooltip("set it to 0.1 or more if you get stuck in wall")]
public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
}
public Camera cam;
public MovementSettings movementSettings = new MovementSettings();
public MouseLook mouseLook = new MouseLook();
public AdvancedSettings advancedSettings = new AdvancedSettings();
private Rigidbody m_RigidBody;
private CapsuleCollider m_Capsule;
private float m_YRotation;
private Vector3 m_GroundContactNormal;
private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;
public Vector3 Velocity
{
get { return m_RigidBody.velocity; }
}
public bool Grounded
{
get { return m_IsGrounded; }
}
public bool Jumping
{
get { return m_Jumping; }
}
public bool Running
{
get
{
#if !MOBILE_INPUT
return movementSettings.Running;
#else
return false;
#endif
}
}
private void Start()
{
m_RigidBody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
mouseLook.Init (transform, cam.transform);
}
private void Update()
{
RotateView();
if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
{
m_Jump = true;
}
}
private void FixedUpdate()
{
GroundCheck();
Vector2 input = GetInput();
if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
{
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;
desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
if (m_RigidBody.velocity.sqrMagnitude <
(movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
{
m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
}
}
if (m_IsGrounded)
{
m_RigidBody.drag = 5f;
if (m_Jump)
{
m_RigidBody.drag = 0f;
m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
m_Jumping = true;
}
if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
{
m_RigidBody.Sleep();
}
}
else
{
m_RigidBody.drag = 0f;
if (m_PreviouslyGrounded && !m_Jumping)
{
StickToGroundHelper();
}
}
m_Jump = false;
}
private float SlopeMultiplier()
{
float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
return movementSettings.SlopeCurveModifier.Evaluate(angle);
}
private void StickToGroundHelper()
{
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) +
advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
{
m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
}
}
}
private Vector2 GetInput()
{
Vector2 input = new Vector2
{
x = CrossPlatformInputManager.GetAxis("Horizontal"),
y = CrossPlatformInputManager.GetAxis("Vertical")
};
movementSettings.UpdateDesiredTargetSpeed(input);
return input;
}
private void RotateView()
{
//avoids the mouse looking if the game is effectively paused
if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;
// get the rotation before it's changed
float oldYRotation = transform.eulerAngles.y;
mouseLook.LookRotation (transform, cam.transform);
if (m_IsGrounded || advancedSettings.airControl)
{
// Rotate the rigidbody velocity to match the new direction that the character is looking
Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
}
}
/// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
private void GroundCheck()
{
m_PreviouslyGrounded = m_IsGrounded;
RaycastHit hitInfo;
if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
{
m_IsGrounded = true;
CurrentlyGrounded = true;
m_GroundContactNormal = hitInfo.normal;
}
else
{
m_IsGrounded = false;
CurrentlyGrounded = false;
m_GroundContactNormal = Vector3.up;
}
if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
{
m_Jumping = false;
}
}
}
}
What should be happening is that it's seen and changes as expected.
Instead, it's reported as nonexisting in the current context.
Don't listen to people who want to make everything static just to access stuff "more easily".
This actually might cause a lot of trouble as soon as you have more than exactly one instances of that class (e.g. if there are two players, or an AI uses the same component).
Another bad side effect is that you won't be able anymore to configure it via the Inspector e.g. for debugging or to give it the desired start value.
What you want to use instead is
moventSettings.CurrentlyGrounded
to access the value of your MovementSettings instance.
Just the same way you did it e.g. in
movementSettings.Running
You can assign it to a global variable.
public static class Globals
{
public static String value = "Sample Value"; // Modifiable
public static readonly String CODE_PREFIX = "TEST-"; // Unmodifiable
}
You can then retrieve the defined values anywhere in your code
String code = Globals.CODE_PREFIX + value.ToString();
I have a homing missile script that seems to work 99% of the time, but every so often one of the missiles will start spiralling out of control and not towards the player. I can't see any reason for it, I can't see a reason for the behaviour in the code and I'm after a pair of fresh eye's to take a look and see if I'm missing something obvious. The script below is attached to each missile.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class missileControl : MonoBehaviour
{
public Transform missileTarget;
public GameObject indicator;
private int scorePerHit = 1;
private int scorePerDestroy = 50;
private int hits = 1;
[Header("Enemy Culling Variables")]
[HideInInspector]
public float distanceToCull = 4f;
[HideInInspector]
private Transform spaceShip;
public Rigidbody missileRigidbody;
[Header("Missile Control Variables")]
public float turn = 0.9f;
private float initialTurn = 0.9f;
public float missileVelocity = 95f;
private float initialMissileVelocity = 95f;
private Vector3 resetMissileVelocity = new Vector3(0f,0f,0f);
private Transform myTransform;
private float wiggleMultiplyer = 40f;
[Header("Firing Audio")]
public float minPitch = 0.9f;
public float maxPitch = 1f;
public AudioClip indicatorClip;
public TrailRenderer trailRenderer;
private bool indicatorOff = true;
private float currentDistance = 100f;
public float indicatorDist = 300f;
private IEnumerator delayAimTimer;
private void Start()
{
spaceShip = LevelVariables.currentLevelVariables.spaceShip.transform; // Player to test if behind
missileTarget = LevelVariables.currentLevelVariables.playerTarget.transform; // Target
missileRigidbody.velocity = resetMissileVelocity;
ResetVariables();
}
private void OnEnable()
{
ResetVariables();
}
private void OnDisable()
{
missileRigidbody.velocity = resetMissileVelocity;
}
void ResetVariables()
{
trailRenderer.enabled = false;
StartCoroutine(DelayTrails());
indicatorOff = true;
turn = Random.Range(initialTurn * 0.85f, initialTurn * 1.15f);
wiggleMultiplyer = Random.Range(0 - (wiggleMultiplyer), wiggleMultiplyer);
missileRigidbody.velocity = resetMissileVelocity;
missileVelocity = Random.Range(initialMissileVelocity * 0.85f, initialMissileVelocity * 1.15f);
missileRigidbody.velocity = transform.forward * missileVelocity;
}
IEnumerator DelayTrails()
{
yield return new WaitForSeconds(0.15f);
trailRenderer.Clear();
trailRenderer.enabled = true;
}
private void FixedUpdate()
{
if (GameStateController.gameStateController.gameState == GameStateController.GameState.PLAYERSTART)
{
if (Vector3.Angle((gameObject.transform.position - spaceShip.position), spaceShip.transform.forward) > 90)
{
if ((gameObject.transform.position - spaceShip.position).sqrMagnitude > distanceToCull * distanceToCull)
{
KillEnemy();
return;
}
}
else
{
if (indicatorOff)
{
currentDistance = Vector3.Distance(missileTarget.position, transform.position);
if (currentDistance <= indicatorDist)
{
indicator.SetActive(true);
PlayAudioSound(indicatorClip);
indicatorOff = false;
}
}
//missileRigidbody.velocity = (transform.forward * missileVelocity) + (transform.right * (Mathf.Sin(Time.time) * wiggleMultiplyer)) + (transform.up * (Mathf.Cos(Time.time) * wiggleMultiplyer));
missileRigidbody.velocity = transform.forward * missileVelocity;
var rocketTargetRotation = Quaternion.LookRotation(missileTarget.position - transform.position);
missileRigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, rocketTargetRotation, turn));
}
}
else
{
StartCoroutine(DestroyGameObject(gameObject, 0f));
}
}
void OnCollisionEnter(Collision hit)
{
switch (hit.gameObject.tag)
{
case "environment":
KillEnemy();
break;
case "enemy":
KillEnemy();
break;
case "enemyBullet":
break;
case "player":
CameraShake.Shake(1f, 0.25f);
float deathScale = Random.Range(5f * transform.localScale.x, 10f * transform.localScale.x);
GameObject fx = ObjectPooler.currentPool.enemyHits.Spawn();
if (fx == null) return;
fx.transform.position = transform.position;
fx.transform.rotation = Quaternion.identity;
fx.transform.parent = hit.transform;
fx.transform.localScale = new Vector3(deathScale, deathScale, deathScale);
fx.SetActive(true);
KillEnemy();
break;
case "playerBullet":
ProcessHit();
if (hits < 1)
{
LevelVariables.currentLevelVariables.scoreBoard.ScoreHit(scorePerDestroy);
KillEnemy();
}
break;
}
}
private void ProcessHit()
{
LevelVariables.currentLevelVariables.scoreBoard.ScoreHit(scorePerHit);
hits = hits - 1;
}
private void KillEnemy()
{
GameObject fx = ObjectPooler.currentPool.enemyDeath.Spawn();
if (fx == null) return;
fx.transform.position = transform.position;
fx.transform.rotation = Quaternion.identity;
fx.transform.parent = LevelVariables.currentLevelVariables.spawnParent;
float deathScale = 1f;
deathScale = Random.Range(1f * transform.localScale.x, 4f * transform.localScale.x);
fx.transform.localScale = new Vector3(deathScale, deathScale, deathScale);
fx.SetActive(true);
StartCoroutine(DestroyGameObject(gameObject, 0f));
}
public void PlayAudioSound(AudioClip clip)
{
LevelVariables.currentLevelVariables.computerAudioSource.volume = 1f;
LevelVariables.currentLevelVariables.computerAudioSource.PlayOneShot(clip);
}
IEnumerator DestroyGameObject(GameObject turnOffObject, float waitTime)
{
yield return new WaitForSeconds(waitTime);
trailRenderer.Clear();
trailRenderer.enabled = false;
turnOffObject.Recycle();
}
}
The section below is the code for creating the missile and is part of the enemy weapon firing script.
GameObject missileObj = ObjectPooler.currentPool.destroyerMissileAmmo.Spawn();
if (missileObj == null) yield break;
CreateMuzzleFlash(muzzleLocation);
//LevelVariables.currentLevelVariables.globalMissileAmount = LevelVariables.currentLevelVariables.globalMissileAmount + 1;
missileObj.transform.localScale = new Vector3(2f, 2f, 2f);
missileObj.transform.position = muzzleLocation.transform.position;
missileObj.transform.rotation = muzzleLocation.transform.rotation;
//missileObj.transform.LookAt(m_target.transform);
missileObj.SetActive(true);
I don't see any problems with this code that would cause a missile not to head towards the player, does anyone have any idea's
Im using Unity and have asked this on there forums however have not had any replies. Ive found this example from a plugin where I am trying to use the kinect to rotate an object using my right hand to rotate it right and the left to rotate left. I have managed to get the object to do this apart from it stops at each side of the object, but cant work out what part of the code is doing this.
Thanks
using UnityEngine;
using System.Collections;
using System;
public class GestureListener : MonoBehaviour, KinectGestures.GestureListenerInterface
{
// GUI Text to display the gesture messages.
public GUIText GestureInfo;
private bool raiselefthand;
private bool raiserighthand;
public bool IsSwipeLeft()
{
if(raiserighthand)
{
raiserighthand = false;
return true;
}
return false;
}
public bool IsSwipeRight()
{
if(raiselefthand)
{
raiselefthand = false;
return true;
}
return false;
}
public void UserDetected(uint userId, int userIndex)
{
// detect these user specific gestures
KinectManager manager = KinectManager.Instance;
manager.DetectGesture(userId, KinectGestures.Gestures.RaiseLeftHand);
manager.DetectGesture(userId, KinectGestures.Gestures.RaiseRightHand);
if(GestureInfo != null)
{
GestureInfo.GetComponent<GUIText>().text = "Swipe left or right to change the slides.";
}
}
public void UserLost(uint userId, int userIndex)
{
if(GestureInfo != null)
{
GestureInfo.GetComponent<GUIText>().text = string.Empty;
}
}
public void GestureInProgress(uint userId, int userIndex, KinectGestures.Gestures gesture,
float progress, KinectWrapper.NuiSkeletonPositionIndex joint, Vector3 screenPos)
{
// don't do anything here
}
public bool GestureCompleted (uint userId, int userIndex, KinectGestures.Gestures gesture,
KinectWrapper.NuiSkeletonPositionIndex joint, Vector3 screenPos)
{
string sGestureText = gesture + " detected";
if(GestureInfo != null)
{
GestureInfo.GetComponent<GUIText>().text = sGestureText;
}
if(gesture == KinectGestures.Gestures.RaiseRightHand)
raiserighthand = true;
else if(gesture == KinectGestures.Gestures.RaiseLeftHand)
raiselefthand = true;
return true;
}
public bool GestureCancelled (uint userId, int userIndex, KinectGestures.Gestures gesture,
KinectWrapper.NuiSkeletonPositionIndex joint)
{
// don't do anything here, just reset the gesture state
return true;
}
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PresentationScript : MonoBehaviour
{
public bool slideChangeWithGestures = true;
public bool slideChangeWithKeys = true;
public float spinSpeed = 5;
public bool autoChangeAlfterDelay = false;
public float slideChangeAfterDelay = 10;
public List<Texture> slideTextures;
public List<GameObject> horizontalSides;
// if the presentation cube is behind the user (true) or in front of the user (false)
public bool isBehindUser = false;
private int maxSides = 0;
private int maxTextures = 0;
private int side = 0;
private int tex = 0;
private bool isSpinning = false;
private float slideWaitUntil;
private Quaternion targetRotation;
private GestureListener gestureListener;
void Start()
{
// hide mouse cursor
Cursor.visible = false;
// calculate max slides and textures
maxSides = horizontalSides.Count;
maxTextures = slideTextures.Count;
// delay the first slide
slideWaitUntil = Time.realtimeSinceStartup + slideChangeAfterDelay;
targetRotation = transform.rotation;
isSpinning = false;
tex = 0;
side = 0;
if(horizontalSides[side] && horizontalSides[side].GetComponent<Renderer>())
{
horizontalSides[side].GetComponent<Renderer>().material.mainTexture = slideTextures[tex];
}
// get the gestures listener
gestureListener = Camera.main.GetComponent<GestureListener>();
}
void Update()
{
// dont run Update() if there is no user
KinectManager kinectManager = KinectManager.Instance;
if(autoChangeAlfterDelay && (!kinectManager || !kinectManager.IsInitialized() || !kinectManager.IsUserDetected()))
return;
if(!isSpinning)
{
if(slideChangeWithKeys)
{
if(Input.GetKeyDown(KeyCode.PageDown))
RotateToNext();
else if(Input.GetKeyDown(KeyCode.PageUp))
RotateToPrevious();
}
if(slideChangeWithGestures && gestureListener)
{
if(gestureListener.IsSwipeLeft())
RotateToNext();
else if(gestureListener.IsSwipeRight())
RotateToPrevious();
}
// check for automatic slide-change after a given delay time
if(autoChangeAlfterDelay && Time.realtimeSinceStartup >= slideWaitUntil)
{
RotateToNext();
}
}
else
{
// spin the presentation
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, spinSpeed * Time.deltaTime);
// check if transform reaches the target rotation. If yes - stop spinning
float deltaTargetX = Mathf.Abs(targetRotation.eulerAngles.x - transform.rotation.eulerAngles.x);
float deltaTargetY = Mathf.Abs(targetRotation.eulerAngles.y - transform.rotation.eulerAngles.y);
if(deltaTargetX < 1f && deltaTargetY < 1f)
{
// delay the slide
slideWaitUntil = Time.realtimeSinceStartup + slideChangeAfterDelay;
isSpinning = false;
}
}
}
private void RotateToNext()
{
// set the next texture slide
tex = (tex + 1) % maxTextures;
if(!isBehindUser)
{
side = (side + 1) % maxSides;
}
else
{
if(side <= 0)
side = maxSides - 1;
else
side -= 1;
}
if(horizontalSides[side] && horizontalSides[side].GetComponent<Renderer>())
{
horizontalSides[side].GetComponent<Renderer>().material.mainTexture = slideTextures[tex];
}
// rotate the presentation
float yawRotation = !isBehindUser ? 360f / maxSides : -360f / maxSides;
Vector3 rotateDegrees = new Vector3(0f, yawRotation, 0f);
targetRotation *= Quaternion.Euler(rotateDegrees);
isSpinning = true;
}
private void RotateToPrevious()
{
// set the previous texture slide
if(tex <= 0)
tex = maxTextures - 1;
else
tex -= 1;
if(!isBehindUser)
{
if(side <= 0)
side = maxSides - 1;
else
side -= 1;
}
else
{
side = (side + 1) % maxSides;
}
if(horizontalSides[side] && horizontalSides[side].GetComponent<Renderer>())
{
horizontalSides[side].GetComponent<Renderer>().material.mainTexture = slideTextures[tex];
}
// rotate the presentation
float yawRotation = !isBehindUser ? -360f / maxSides : 360f / maxSides;
Vector3 rotateDegrees = new Vector3(0f, yawRotation, 0f);
targetRotation *= Quaternion.Euler(rotateDegrees);
isSpinning = true;
}
}
I have managed to get the object to do this apart from it stops at each side of the object, but cant work out what part of the code is doing this.
I understand you ask for help finding which parts are involved in the rotation.
As such, I looked through the scripts and noticed 2 sections in the PresentationScript.
This part in the Update() method. Based on the code and the comments that are part of it.
// spin the presentation
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, spinSpeed * Time.deltaTime);
// check if transform reaches the target rotation. If yes - stop spinning
float deltaTargetX = Mathf.Abs(targetRotation.eulerAngles.x - transform.rotation.eulerAngles.x);
float deltaTargetY = Mathf.Abs(targetRotation.eulerAngles.y - transform.rotation.eulerAngles.y);
if(deltaTargetX < 1f && deltaTargetY < 1f)
{
// delay the slide
slideWaitUntil = Time.realtimeSinceStartup + slideChangeAfterDelay;
isSpinning = false;
}
This line in the Start() method is also involved.
targetRotation = transform.rotation;
A transform controls the position, scaling and as is relevant for this case, also the rotation of an object.