Unity camera starting position - c#

Hello so I created a camera for a RTS game I'm making but on start the camera is on the minHight position and I cant figure out how to change it hope someone helps the code is a bit of a mess its just for a test here is the code I want it to start from the maxHight position that is given and not on the minHight .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RtsCamera : MonoBehaviour {
public float zoomSensitivy = 15;
private Transform m_Transform;
public float screenEdgeBorder = 25f;
public bool useScreenEdgeInput = true;
public float screenEdgeMovementSpeed = 3f;
// zoom stuff
public float heightDampening = 5f;
public float scrollWheelZoomingSensitivity = 25f;
public float maxHeight = 10f; //maximal height
public float minHeight = 15f; //minimnal height
public LayerMask groundMask = -1;
public bool autoHeight = true;
public bool limitMap = true;
public float limitX = 50f; //x limit of map
public float limitZ = 50f; //z limit of map
private float zoomPos = 0; //value in range (0, 1) used as t in Matf.Lerp
public bool useScrollwheelZooming = true;
Vector3 tempPos;
public string zoomingAxis = "Mouse ScrollWheel";
private float ScrollWheel
{
get { return Input.GetAxis(zoomingAxis); }
}
private Vector2 MouseAxis
{
get { return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y")); }
}
private Vector2 MouseInput
{
get { return Input.mousePosition; }
}
private void Start()
{
m_Transform = transform;
}
// Update is called once per frame
void Update () {
Move();
LimitPosition();
HeightCalculation();
}
private void Move()
{
if (useScreenEdgeInput)
{
Vector3 desiredMove = new Vector3();
Rect leftRect = new Rect(0, 0, screenEdgeBorder, Screen.height);
Rect rightRect = new Rect(Screen.width - screenEdgeBorder, 0, screenEdgeBorder, Screen.height);
Rect upRect = new Rect(0, Screen.height - screenEdgeBorder, Screen.width, screenEdgeBorder);
Rect downRect = new Rect(0, 0, Screen.width, screenEdgeBorder);
desiredMove.x = leftRect.Contains(MouseInput) ? -1 : rightRect.Contains(MouseInput) ? 1 : 0;
desiredMove.z = upRect.Contains(MouseInput) ? 1 : downRect.Contains(MouseInput) ? -1 : 0;
desiredMove *= screenEdgeMovementSpeed;
desiredMove *= Time.deltaTime;
desiredMove = Quaternion.Euler(new Vector3(0f, transform.eulerAngles.y, 0f)) * desiredMove;
desiredMove = m_Transform.InverseTransformDirection(desiredMove);
m_Transform.Translate(desiredMove, Space.Self);
}
}
private void LimitPosition()
{
if (!limitMap)
return;
m_Transform.position = new Vector3(Mathf.Clamp(m_Transform.position.x, -limitX, limitX),
m_Transform.position.y,
Mathf.Clamp(m_Transform.position.z, -limitZ, limitZ));
}
private void HeightCalculation()
{
float distanceToGround = DistanceToGround();
if (useScrollwheelZooming)
zoomPos += ScrollWheel * Time.deltaTime * scrollWheelZoomingSensitivity;
zoomPos = Mathf.Clamp01(zoomPos);
float targetHeight = Mathf.Lerp(minHeight, maxHeight, zoomPos);
float difference = 0;
if (distanceToGround != targetHeight)
difference = targetHeight - distanceToGround;
m_Transform.position = Vector3.Lerp(m_Transform.position,
new Vector3(m_Transform.position.x, targetHeight + difference, m_Transform.position.z), Time.deltaTime * heightDampening);
}
private float DistanceToGround()
{
Ray ray = new Ray(m_Transform.position, Vector3.down);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, groundMask.value))
return (hit.point - m_Transform.position).magnitude;
return 0f;
}
}

Set the value of the variable zoomPos on line 25 to either 1 or 0 depending on whether you want it at the min height or the max height, you could do this either in the Start() or just at the declaration of the variable.
This is because in the HeightCalculation function it sets the height to somewhere between the min and max based off the value of zoomPos, as you use the scrollwheel this value changes and so does the zoom. Altering zoomPos before you run the game allows you to effectively set a default starting height.

Related

Offscreen target indicators - Unity 2D

I'm trying to point to an object when it's off-screen. The objects are static.
public class SpawnIndicator : MonoBehaviour
{
public Camera UIcamera;
public GameObject point;
public Canvas canvas;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (point.GetComponent<Renderer>().isVisible)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.clear;
}
else
{
gameObject.GetComponent<SpriteRenderer>().color = Color.white;
//POSITION
Vector3 pointPos = UIcamera.WorldToScreenPoint(point.transform.position);
pointPos.z = 0;
pointPos.x = Mathf.Clamp(pointPos.x, (Screen.width * 0.01f), (Screen.width * 0.99f));
pointPos.y = Mathf.Clamp(pointPos.y, (Screen.height * 0.01f), (Screen.height * 0.99f));
pointPos -= new Vector3((Screen.width/2), (Screen.height/2), 0);
gameObject.transform.localPosition = pointPos;
//ROTATION
gameObject.GetComponent<SpriteRenderer>().color = Color.white;
Vector3 vectorToTarget = point.transform.position - gameObject.transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
angle -= 90;
Quaternion newRotation = Quaternion.AngleAxis(angle, Vector3.forward);
gameObject.transform.rotation = newRotation;
}
}
}
This works fine when the screen size is 1920x1080 (the reference size for my canvas). However at lower sizes, the objects sit awawy from the edges, and in larger sizes they sit outside of the edges.
Figured it out.
WorldToScreenPoint was returning a value based on the reference resolution (1920x1080) so different resolutions ended up mismatched. I think that's what was going wrong, regardless, I've got the solution.
I found this method to convert a world position to canvas position.
public static Vector3 WorldToScreenSpace(Vector3 worldPos, Camera cam, RectTransform area)
{
Vector3 screenPoint = cam.WorldToScreenPoint(worldPos);
screenPoint.z = 0;
Vector2 screenPos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(area, screenPoint, cam, out screenPos))
{
return screenPos;
}
return screenPoint;
}
I'd also changed the rest of the code a bit while trying to fix this before finding that solution (and coincidentally was using the canvas size) so here's the full script:
public class SpawnIndicator : MonoBehaviour
{
public Camera UIcamera;
public GameObject point;
public Canvas canvas;
Vector3 pointPos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (point.GetComponent<Renderer>().isVisible)
{
gameObject.GetComponent<SpriteRenderer>().color = Color.clear;
}
else
{
gameObject.GetComponent<SpriteRenderer>().color = Color.white;
Vector3[] canvasPoints = new Vector3[4];
canvas.GetComponent<RectTransform>().GetLocalCorners(canvasPoints);
Vector3 pointPos = WorldToScreenSpace(point.transform.position, UIcamera, canvas.GetComponent<RectTransform>());
float xMin = canvasPoints[0].x * 0.98f;
float xMax = canvasPoints[2].x * 0.98f;
float yMin = canvasPoints[0].y * 0.8f;
float yMax = canvasPoints[2].y * 0.98f;
//POSITION
if (pointPos.x <= xMin) pointPos.x = xMin;
if (pointPos.x >= xMax) pointPos.x = xMax;
if (pointPos.y <= yMin) pointPos.y = yMin;
if (pointPos.y >= yMax) pointPos.y = yMax;
pointPos.z = 0f;
gameObject.transform.localPosition = pointPos;
//ROTATION
gameObject.GetComponent<SpriteRenderer>().color = Color.white;
Vector3 vectorToTarget = point.transform.position - gameObject.transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
angle -= 90;
Quaternion newRotation = Quaternion.AngleAxis(angle, Vector3.forward);
gameObject.transform.rotation = newRotation;
}
}
public static Vector3 WorldToScreenSpace(Vector3 worldPos, Camera cam, RectTransform area)
{
Vector3 screenPoint = cam.WorldToScreenPoint(worldPos);
screenPoint.z = 0;
Vector2 screenPos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(area, screenPoint, cam, out screenPos))
{
return screenPos;
}
return screenPoint;
}
}

Find an angle and velocity to launch the projectile with to reach a specific point

I am trying to make a cannon that shoots a target located in a 3D world in Unity... I hava a LaunchConfig enum ->
public enum LauncherConfig
{
CalculateNone = 0,
CalculateAngle = 1,
CalculateVelocity = 2,
CalculateBoth = 3
}
When CalculateAngle is selected the user can input the Initial Velocity for the projectile and the angle the projectile needs to be launched at to reach the target has to be calculated.
Same for CalculateVelocity.
CalculateNone allows the user to input both the values and CalculateBoth calculates both the values.
What equations do I use to calculate the values so that they line up, i.e. when CalculateAngle is selected the velocity calculated should be such that the projectile looks natural coming out of the barrel. Same for CalculateBoth, the angle should be calculated so that the velocity calculated will launch the projectile strait out the barrel and not any other direction.
I have my current location (Vector3), target location (Vector3).
The calculated angle will affect the x-rotation of the cannon.
The y-rotation is lined up with the target already so that it faces the target;
Here is the code for the class
using System;
using UnityEngine;
public class Launcher : MonoBehaviour
{
[SerializeField] private LauncherSettings settings = default;
[SerializeField] private Transform target = default;
private Transform partToRotateY;
private Transform partToRotateX;
private Transform projectileSpawnPosition;
private float x;
private float y;
private Vector3 velocity;
private void Awake()
{
partToRotateX = transform.GetChild(0);
partToRotateY = transform.GetChild(1);
projectileSpawnPosition = partToRotateX.GetChild(0);
settings.inputController = new InputActions.Launcher();
settings.inputController.Automatic.Launch.performed += _ => Shoot();
}
private void Update()
{
CalculateVelocity();
CalculateAngle();
LookAtTarget();
Shoot();
}
private void OnEnable()
{
settings.inputController.Enable();
}
private void OnDisable()
{
settings.inputController.Disable();
}
private void LookAtTarget()
{
Vector3 direction = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(direction);
y = lookRotation.eulerAngles.y;
Quaternion rotationY = Quaternion.Euler(0f, y, 0f);
Quaternion rotationX = Quaternion.Euler(-x, y, 0f);
partToRotateY.rotation = Quaternion.Slerp(partToRotateY.rotation, rotationY, Time.deltaTime * settings.rotationSpeed);
partToRotateX.rotation = Quaternion.Slerp(partToRotateX.rotation, rotationX, Time.deltaTime * settings.rotationSpeed);
}
private float nextTimeToFire = 0f;
private void Shoot()
{
nextTimeToFire -= Time.deltaTime;
if (!(nextTimeToFire <= 0f)) return;
nextTimeToFire = 1 / settings.fireRate;
var rb = Instantiate(settings.projectilePrefab, projectileSpawnPosition.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.velocity = velocity;
}
private void CalculateAngle()
{
if (settings.launcherConfig == LauncherConfig.CalculateVelocity ||
settings.launcherConfig == LauncherConfig.CalculateNone)
{
x = Mathf.Clamp(settings.launchAngle, -20f, 80f);
}
else
{
var position = target.position;
var position1 = transform.position;
var dist = Math.Sqrt(Mathf.Pow((position.x - position1.x), 2) + Mathf.Pow((position.y - position1.y), 2));
var a = Physics.gravity.y * Mathf.Pow((float) dist, 2) / (2 * Mathf.Pow(velocity.magnitude, 2));
var b = (float) -dist;
var c = position.z - position1.z + a;
x = (float) Math.Atan2(QuadraticRoot(a, b, c), 1);
Debug.Log(x);
}
}
private void CalculateVelocity()
{
if (settings.launcherConfig == LauncherConfig.CalculateAngle ||
settings.launcherConfig == LauncherConfig.CalculateNone)
{
velocity = partToRotateX.forward * settings.velocity;
}
else
{
float h;
if (settings.launcherConfig == LauncherConfig.CalculateBoth && settings.calculateMaxHeight)
{
h = Mathf.Abs(target.position.y - partToRotateX.position.y * settings.maxHeightMultiplier);
}
else
{
h = settings.maxHeight;
}
var position = partToRotateX.position;
var position1 = target.position;
var gravity = Physics.gravity.y;
var displacementY = position1.y - position.y;
var displacementXZ = new Vector3 (position1.x - position.x, 0, position1.z - position.z);
var time = Mathf.Sqrt(-2*h/gravity) + Mathf.Sqrt(2*(displacementY - h)/gravity);
var velocityY = Vector3.up * Mathf.Sqrt (-2 * gravity * h);
var velocityXZ = displacementXZ / time;
velocity = velocityXZ + velocityY * -Mathf.Sign(gravity);
}
}
private double QuadraticRoot(double a, double b, double c){
double D = Math.Pow(b, 2) - (4 * a * c);
return (-b + Math.Sqrt(D)) / (2 * a);
}
}
The LauncherSettings Class...
using Attributes.DrawIf;
using Attributes.DrawIfAndOr;
using UnityEngine;
[CreateAssetMenu]
public class LauncherSettings : ScriptableObject
{
public InputActions.Launcher inputController;
public LauncherConfig launcherConfig = LauncherConfig.CalculateVelocity;
public GameObject projectilePrefab = default;
public float rotationSpeed = 5f;
public float fireRate = 5f;
[DrawIfAndOr(nameof(launcherConfig), LauncherConfig.CalculateAngle, LauncherConfig.CalculateNone)]
public float velocity = 200f;
[DrawIfAndOr(nameof(launcherConfig), LauncherConfig.CalculateVelocity, LauncherConfig.CalculateNone)]
public float launchAngle = 0f;
[DrawIf(nameof(launcherConfig), LauncherConfig.CalculateBoth)]
public bool calculateMaxHeight = true;
[DrawIf(nameof(calculateMaxHeight), false)]
public float maxHeight;
[DrawIf(nameof(calculateMaxHeight), true)]
public float maxHeightMultiplier = 5f;
}
The DrawIf and DrawIfAndOr are attributes that hide the vaule in inspector if the first paramerter is equal to the other. You can completely ignore them. The calculation of Velocity is by
Sebastian Lague (https://www.youtube.com/channel/UCmtyQOKKmrMVaKuRXz02jbQ) in his Kinematic Equations (E03: ball problem) (https://youtu.be/IvT8hjy6q4o). The calculation of the angle is from an answer on my other question (Find an angle to launch the projectile at to reach a specific point).
Any help is appreciated...
Thanks...

How can i make the camera to lookat the next target and then rotate and move to the next target?

The first script is just making the camera to move over the terrain this script i'm not changing anything. The second script is PatrolData with that i feed the first script with data. The last script is the LookAt that should rotate the camera just a bit before moving to the next target(waypoint).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyToOverTerrain : MonoBehaviour
{
public Transform target;
public float desiredHeight = 10f;
public float flightSmoothTime = 10f;
public float maxFlightspeed = 10f;
public float flightAcceleration = 1f;
public float levelingSmoothTime = 0.5f;
public float maxLevelingSpeed = 10000f;
public float levelingAcceleration = 2f;
private Vector3 flightVelocity = Vector3.zero;
private float heightVelocity = 0f;
private void LateUpdate()
{
Vector3 position = transform.position;
float currentHeight = position.y;
if ((bool)target && flightAcceleration > float.Epsilon)
{
position = Vector3.SmoothDamp(position, target.position, ref flightVelocity, flightSmoothTime / flightAcceleration, maxFlightspeed, flightAcceleration * Time.deltaTime);
}
if (levelingAcceleration > float.Epsilon)
{
float targetHeight = Terrain.activeTerrain.SampleHeight(position) + desiredHeight;
position.y = Mathf.SmoothDamp(currentHeight, targetHeight, ref heightVelocity, levelingSmoothTime / levelingAcceleration, maxLevelingSpeed, levelingAcceleration * Time.deltaTime);
}
transform.position = position;
}
}
Then the data script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PatrolData
{
public Transform target = null;
public float minDistance = 5f;
public float lingerDuration = 5f;
public float desiredHeight = 10f;
public float flightSmoothTime = 10f;
public float maxFlightspeed = 10f;
public float flightAcceleration = 1f;
public float levelingSmoothTime = 0.5f;
public float maxLevelingSpeed = 10000f;
public float levelingAcceleration = 2f;
}
public class PatrolOverTerrain : MonoBehaviour
{
public FlyToOverTerrain flyOverTerrain;
public enum PatrolMode { Clamp, Wrap, PingPong };
public PatrolData[] patrolPoints;
public PatrolMode mode = PatrolMode.Wrap;
private int iterator = 0;
private int index = 0;
private float lingerDuration = 0f;
public Vector3 distanceFromTarget;
private void OnEnable()
{
if (patrolPoints.Length > 0)
{
lingerDuration = patrolPoints[index].lingerDuration;
}
}
private void Update()
{
int length = patrolPoints.Length;
if (!flyOverTerrain) return;
if (patrolPoints.Length < 1) return;
if (index < 0) return;
var patrol = patrolPoints[index];
if (lingerDuration <= 0)
{
iterator++;
switch (mode)
{
case PatrolMode.Clamp:
index = (iterator >= length) ? -1 : iterator;
break;
case PatrolMode.Wrap:
iterator = Modulus(iterator, length);
index = iterator;
break;
case PatrolMode.PingPong:
iterator = Modulus(iterator, length * 2);
index = length - Mathf.Abs(length - iterator);
break;
}
if (index < 0) return;
patrol = patrolPoints[index];
flyOverTerrain.target = patrol.target;
flyOverTerrain.desiredHeight = patrol.desiredHeight;
flyOverTerrain.flightSmoothTime = patrol.flightSmoothTime;
flyOverTerrain.maxFlightspeed = patrol.maxFlightspeed;
flyOverTerrain.flightAcceleration = patrol.flightAcceleration;
flyOverTerrain.levelingSmoothTime = patrol.levelingSmoothTime;
flyOverTerrain.maxLevelingSpeed = patrol.maxLevelingSpeed;
flyOverTerrain.levelingAcceleration = patrol.levelingAcceleration;
lingerDuration = patrolPoints[index].lingerDuration;
}
Vector3 targetOffset = Vector3.zero;
if ((bool)patrol.target)
{
targetOffset = transform.position - patrol.target.position;
}
float sqrDistance = patrol.minDistance * patrol.minDistance;
if (targetOffset.sqrMagnitude <= sqrDistance)
{
flyOverTerrain.target = null;
lingerDuration -= Time.deltaTime;
}
else
{
flyOverTerrain.target = patrol.target;
}
distanceFromTarget = transform.position - patrol.target.position;
}
private int Modulus(int baseNumber, int modulus)
{
return (modulus == 0) ? baseNumber : baseNumber - modulus * (int)Mathf.Floor(baseNumber / (float)modulus);
}
}
And the lookat script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtCamera : MonoBehaviour {
//values that will be set in the Inspector
public Transform target;
public float RotationSpeed;
//values for internal use
private Quaternion _lookRotation;
private Vector3 _direction;
// Update is called once per frame
void Update()
{
//find the vector pointing from our position to the target
_direction = (target.position - transform.position).normalized;
//create the rotation we need to be in to look at the target
_lookRotation = Quaternion.LookRotation(_direction);
//rotate us over time according to speed until we are in the required rotation
transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * RotationSpeed);
}
}
All scripts are attached to the Main Camera. Until now it was working fine the camera moved between the targets. Now what i want to do is when the camera stop near each target just a bit before the camera start moving to the next target make a rotation to be facing to the target it's going to be moving to.
The problem is i don't know how to make it wait and how much and when to start the rotation in the LookAtCamera script.
Now what it does when running the game it's start rotating right away to the next target(in inspector i dragged for testing the second target).
My problem is how to work with the LookAtCamera script.
Found how to do it.
First in the LookAtCamera script that attached it to the Main Camera i also check that there is a target existing in the Update function:
if (target)
so the Update function:
void Update()
{
//find the vector pointing from our position to the target
if (target)
_direction = (target.position - transform.position).normalized;
//create the rotation we need to be in to look at the target
_lookRotation = Quaternion.LookRotation(_direction);
//rotate us over time according to speed until we are in the required rotation
transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * RotationSpeed);
}
Then in the script PatrolData:
The script PatrolData can be attached to any gameobject in this case i attached it to the Main Camera too.
In the top of FlyToVerTerrain i added:
public LookAtCamera lookAtCamera;
Then in the Update function:
lookAtCamera.target = patrol.target;
lookAtCamera.RotationSpeed = 3;
Then at this part:
if (targetOffset.sqrMagnitude <= sqrDistance)
{
flyOverTerrain.target = null;
lookAtCamera.target = null;
lingerDuration -= Time.deltaTime;
}
else
{
flyOverTerrain.target = patrol.target;
lookAtCamera.target = patrol.target;
}
In the end all the 3 scripts make that the camera will move to each waypoint(target), The camera will rotate and will face to the next waypoint before moving to the next waypoint.
Working perfect.

Player Movement using joystick based on camera facing

I am developing an offline FPS multiplayer game.
When the Player Rotation value is (0,0,0), then Player moves perfectly in direction. However, my problem is when I rotate the camera using touch input. The player can also rotate his face and press the joystick button for moving the player, but then the player should not move the direction the camera is facing.
My Joystick Script For Player
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler,IPointerDownHandler {
private Image bgImg;
private Image JoyStickImage;
private Vector3 InputVector;
private void Start(){
bgImg = GetComponent<Image> ();
JoyStickImage = transform.GetChild (0).GetComponent<Image> ();
}
public virtual void OnDrag(PointerEventData ped){
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle (bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos)) {
pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
pos.y = (pos.y / bgImg.rectTransform.sizeDelta.y);
InputVector = new Vector3 (pos.x * 2 + 1, 0, pos.y * 2 - 1);
InputVector = (InputVector.magnitude > 1) ? InputVector.normalized : InputVector;
JoyStickImage.rectTransform.anchoredPosition = new Vector3 (InputVector.x * (bgImg.rectTransform.sizeDelta.x / 2.5f),
InputVector.z * (bgImg.rectTransform.sizeDelta.y / 2.5f));
}
}
public virtual void OnPointerDown(PointerEventData ped){
OnDrag (ped);
}
public virtual void OnPointerUp(PointerEventData ped){
InputVector = Vector3.zero;
JoyStickImage.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal(){
if (InputVector.x != 0) {
return InputVector.x;
} else {
return Input.GetAxis ("Horizontal");
}
}
public float Vertical(){
if (InputVector.z != 0)
return InputVector.z;
else
return Input.GetAxis ("Vertical");
}
}
My Camera Rotation Script Using Input Touch
public class SwipeCam : MonoBehaviour {
private Vector3 firstPoint;
private Vector3 secondPoint;
private float xAngle = 0.0f;
private float yAngle = 0.0f;
private float xAngleTemp = 0.0f;
private float yAngleTemp = 0.0f;
void Start(){
xAngle = 0.0f;
yAngle = 0.0f;
this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);
}
void Update() {
if (Input.touchCount > 0) {
for (int i = 0; i < Input.touchCount; i++) {
Touch touch = Input.GetTouch (i);
if (touch.position.x > Screen.width / 2) {
if (touch.phase == TouchPhase.Began) {
firstPoint = Input.GetTouch (0).position;
xAngleTemp = xAngle;
yAngleTemp = yAngle;
}
if (touch.phase == TouchPhase.Moved) {
secondPoint = Input.GetTouch (0).position;
xAngle = xAngleTemp + (secondPoint.x - firstPoint.x) * 180.0f / Screen.width;
yAngle = yAngleTemp + (secondPoint.y - firstPoint.y) * 180.0f / -Screen.height;
yAngle = Mathf.Clamp (yAngle, -30f, 30f);
this.transform.rotation = Quaternion.Euler (yAngle, xAngle, 0.0f);
this.gameObject.GetComponentInParent<FPScontroller> ().transform.rotation = Quaternion.Euler (0.0f, xAngle, 0.0f);
//this.gameObject.GetComponentInParent<FPScontroller> ().transform.rotation = Quaternion.LookRotation(Vector3.forward,Vector3.up);
}
}
}
}
}
}
Where should I change my code to fix the facing the camera direction to player issue.
That is my Player Script (FPSController.cs)
public class FPScontroller : MonoBehaviour {
// Should this script respond to input?
public bool canControl = true;
public GameObject lookObj; //This is root object that containc MainCamera, Weapons etc.
public GameObject joystick;
bool useFixedUpdate = false;
//Check when run, walk or when can run or not
[HideInInspector]
public bool Running ;
[HideInInspector]
public bool Walking;
[HideInInspector]
public bool canRun;
[HideInInspector]
public Vector3 rorationDir;
//Ladder variables
private GameObject mainCamera = null;
[HideInInspector]
public bool onLadder = false;
//private float ladderHopSpeed = 6.0f;
// For the next variables, #System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The current global direction we want the character to move in.
[System.NonSerialized]
public Vector3 inputMoveDirection = Vector3.zero;
// Is the jump button held down? We use this interface instead of checking
// for the jump button directly so this script can also be used by AIs.
[System.NonSerialized]
public bool inputJump = false;
[HideInInspector]
public bool inputRun = false;
[HideInInspector]
public bool inputCrouch = false;
[HideInInspector]
public bool inputProne = false;
[System.Serializable]
public class FPScontrollerMovement {
// The maximum horizontal speed when moving
[HideInInspector]
public float maxForwardSpeed = 10.0f;
[HideInInspector]
public float maxSidewaysSpeed = 10.0f;
[HideInInspector]
public float maxBackwardsSpeed = 10.0f;
//Run and walk variables
public float WalkSpeed = 6.0f;
public float RunSpeed = 9.0f;
//Crouch
public bool canCrouch = true;
public float CrouchSpeed = 3.0f;
public float crouchHeight = 1.5f;
public float crouchSmooth = 8;
//prone
public bool canProne = true;
public float ProneSpeed = 1.5f;
public float proneHeight = 0.7f;
// Curve for multiplying speed based on slope (negative = downwards)
public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0));
// How fast does the character change speeds? Higher is faster.
public float maxGroundAcceleration = 30.0f;
public float maxAirAcceleration = 20.0f;
// The gravity for the character
public float gravity = 10.0f;
public float maxFallSpeed = 20.0f;
[HideInInspector]
public bool enableGravity = true;
// For the next variables, #System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
// Very handy for organization!
// The last collision flags returned from controller.Move
[System.NonSerialized]
public CollisionFlags collisionFlags;
// We will keep track of the character's current velocity,
[System.NonSerialized]
public Vector3 velocity;
// This keeps track of our current velocity while we're not grounded
[System.NonSerialized]
public Vector3 frameVelocity = Vector3.zero;
[System.NonSerialized]
public Vector3 hitPoint = Vector3.zero;
[System.NonSerialized]
public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0);
}
public FPScontrollerMovement movement = new FPScontrollerMovement();
void Awake () {
if (GetComponent<NetworkView> ().isMine) {
joystick = GameObject.Find ("Joystick");
controller = gameObject.GetComponent<CharacterController>();
standartHeight = controller.height;
/*if(GameObject.FindWithTag("LookObject") != null){
lookObj = GameObject.FindWithTag("LookObject");
}*/
centerY = controller.center.y;
tr = transform;
canRun = true;
canStand = true;
StartCoroutine(setupBools());
}
}
void Update () {
if (GetComponent<NetworkView> ().isMine) {
if (!useFixedUpdate) {
UpdateFunction ();
}
movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;
//Run input
if (Input.GetAxis ("Vertical") > 0.1f && inputRun && canRun && !onLadder && Walking) {
if (canStand && canStandCrouch) {
OnRunning ();
}
} else {
OffRunning ();
}
//Check when walk or not
if ((movement.velocity.x > 0.01f || movement.velocity.z > 0.01f) || (movement.velocity.x < -0.01f || movement.velocity.z < -0.01f)) {
RunAnimation1 ();
Debug.Log ("Forward");
Walking = true;
}else if (movement.velocity.x > 0.01f) {
Walking = true;
Debug.Log ("Right");
} else if (movement.velocity.x < -0.01f) {
Walking = true;
Debug.Log ("Left");
} else {
RunAnimation ();
Walking = false;
}
if (!canControl)
return;
if (movement.canCrouch) {
if (!onLadder) {
Crouch ();
}
}
if (movement.canProne) {
if (!onLadder) {
Prone ();
}
}
if (onLadder) {
grounded = false;
crouch = false;
prone = false;
}
if (!crouch && !prone && controller.height < standartHeight - 0.01f) {
controller.height = Mathf.Lerp (controller.height, standartHeight, Time.deltaTime / movement.crouchSmooth);
controller.center = new Vector3 (controller.center.x, Mathf.Lerp (controller.center.y, centerY, Time.deltaTime / movement.crouchSmooth), controller.center.z);
lookObj.transform.localPosition = new Vector3 (lookObj.transform.localPosition.x, Mathf.Lerp (lookObj.transform.localPosition.y, standartHeight, Time.deltaTime / movement.crouchSmooth), lookObj.transform.localPosition.z);
}
}
}
void RunAnimation(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 0);
}
void RunAnimation1(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 1);
}
void RunAnimation2(){
GetComponent<NetworkView> ().RPC ("SysnAnimation", RPCMode.All, 2);
}
[RPC]
void SysnAnimation(int index){
if (index == 0) {
GetComponent<Animator> ().Play ("Idle Aim");
} else if (index == 1) {
GetComponent<Animator> ().Play ("Walk Aiming");
} else if (index == 2) {
GetComponent<Animator> ().Play ("Jump");
}
}
void OnRunning (){
Debug.Log ("Run");
Running = true;
movement.maxForwardSpeed = movement.RunSpeed;
movement.maxSidewaysSpeed = movement.RunSpeed;
//Make bigger extra height when player run to increase jump distance
jumping.extraHeight = jumping.baseHeight + 0.15f;
}
void OffRunning (){
Running = false;
if(crouch || prone)
return;
movement.maxForwardSpeed = movement.WalkSpeed;
movement.maxSidewaysSpeed = movement.WalkSpeed;
movement.maxBackwardsSpeed = movement.WalkSpeed/2;
//Change extraheight value to default when player walk
jumping.extraHeight = jumping.baseHeight;
}}
Your camera and joystick code looks fine, but that's not where the problem is.
I'll assume your player movement code looks something like this:
Get input X and Y
Move player right by X, forward by Y
In code form, that might look something like this:
//returns the world-space direction that player wants to move
Vector3 GetDesiredMovement(float inputForward, float inputRight) {
//get a vector pointing to player's right
Vector3 dirRight = Camera.main.transform.right;
dirRight.y = 0f;
dirRight.Normalize();
//get a vector pointing to player's front
Vector3 dirForward = Camera.main.transform.forward;
dirForward.y = 0f;
dirForward.Normalize();
//calculate desired movement based on input
Vector3 desiredMovement = (dirForward * inputForward) + (dirRight * inputRight);
desiredMovement.Normalize();
return desiredMovement;
}
What if "right" and "forward" need to be relative to some other object in the scene, such as a camera? It's easier than you might think: just read those values directly from the camera's transform component.
You could do that by replacing just two lines from the above example:
Vector3 dirRight = Camera.main.transform.right;
Vector3 dirForward = Camera.main.transform.forward;
I solved the problem of basing player movement of the camera's direction.
In my Player's script there are two lines that read joystick input:
movement.velocity.x = joystick.GetComponent<VirtualJoystick> ().Horizontal () * 5f;
movement.velocity.z = joystick.GetComponent<VirtualJoystick> ().Vertical () * 5f;`
I changed them to this:
Vector3 DirectionVector =
new Vector3 (joystick.GetComponent<VirtualJoystick> ().Horizontal (), 0f, joystick.GetComponent<VirtualJoystick> ().Vertical ());
movement.velocity = transform.rotation * DirectionVector * 10f;
Directly add joystick value in movement vector. I just multiply it to the joystick input vector and solve my problem.
Now the player moves based on the player rotation and where the camera is facing.
Thanks everyone for help.

wander & chase AI code not working

Put together an enemy AI system for an enemy in which it should wander around idly when the player is not within distance to the enemy and when player is within enemy distance it should initiate chase behaviour and chase after player until player has managed to exit out of the enemy's chase radius.
Currently the enemy is able to wonder freely yet when the player comes within proximity of the enemy the enemy will carry on wandering instead of chasing player.
Anyone help me fix this problem?
Code is as follows.
public enum AIState
{
Chasing,
Wander
}
private float maxSpeed;
private float maxRotation;
private float chaseDistance;
private float hysteresis;
private Texture2D texture;
private Vector2 drawingOrigin;
private Vector2 position;
public AIState aiState = AIState.Wander;
private float orientation;
private Random random = new Random();
private Rectangle viewportbounds;
public Rectangle boundingBox;
public Vector2 playerPosition;
private Vector2 heading;
public Virtual_Aliens(Rectangle pos, Rectangle b)
{
position = new Vector2(300, 400);
boundingBox = new Rectangle(pos.X, pos.Y, pos.Width, pos.Height);
viewportbounds = new Rectangle(b.X, b.Y, b.Width, b.Height);
orientation = 0.0f;
heading = new Vector2(0, 0);
maxSpeed = 2.0f;
maxRotation = 0.20f;
hysteresis = 15.0f;
chaseDistance = 250.0f;
Thread.Sleep(200);
random = new Random();
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>("images/asteroid");
}
private Vector2 OrientationAsVector(float orien)
{
Vector2 orienAsVect;
orienAsVect.X = (float)Math.Cos(orien);
orienAsVect.Y = (float)Math.Sin(orien);
return orienAsVect;
}
Vector2 wanderPosition = new Vector2();
public void Wander()
{
// the max +/- the agent will wander from its current position
float wanderLimits = 0.5f;
// this defines what proportion of its maxRotation speed the agent will turn
float turnFactor = 0.15f;
// randomly define a new position
wanderPosition.X += MathHelper.Lerp(-wanderLimits, wanderLimits, (float)random.NextDouble());
wanderPosition.Y += MathHelper.Lerp(-wanderLimits, wanderLimits, (float)random.NextDouble());
if (wanderPosition != Vector2.Zero)
{
wanderPosition.Normalize();
}
orientation = TurnToFace(wanderPosition, orientation, turnFactor * maxRotation);
heading = OrientationAsVector(orientation);
position += heading * 0.5f * maxSpeed;
WrapForViewport();
}
private void WrapForViewport()
{
if (position.X < 0)
{
position.X = viewportbounds.Width;
}
else if (position.X > viewportbounds.Width)
{
position.X = 0;
}
if (position.Y < 0)
{
position.Y = viewportbounds.Height;
}
else if (position.Y > viewportbounds.Height)
{
position.Y = 0;
}
}
private float WrapAngle(float radian)
{
while (radian < -MathHelper.Pi)
{
radian += MathHelper.TwoPi;
}
while (radian > MathHelper.Pi)
{
radian -= MathHelper.TwoPi;
}
return radian;
}
private float TurnToFace(Vector2 steering, float currentOrientation, float turnSpeed)
{
float newOrientation;
float desiredOrientation;
float orientationDifference;
float x = steering.X;
float y = steering.Y;
// the desiredOrientation is given by the steering vector
desiredOrientation = (float)Math.Atan2(y, x);
// find the difference between the orientation we need to be
// and our current Orientation
orientationDifference = desiredOrientation - currentOrientation;
// now using WrapAngle to get result from -Pi to Pi
// ( -180 degrees to 180 degrees )
orientationDifference = WrapAngle(orientationDifference);
// clamp that between -turnSpeed and turnSpeed.
orientationDifference = MathHelper.Clamp(orientationDifference, -turnSpeed, turnSpeed);
// the closest we can get to our target is currentAngle + orientationDifference.
// return that, using WrapAngle again.
newOrientation = WrapAngle(currentOrientation + orientationDifference);
return newOrientation;
}
public void Update(GameTime gameTime)
{
if (aiState == AIState.Wander)
{
chaseDistance -= hysteresis / 2;
}
else if (aiState == AIState.Chasing)
{
chaseDistance += hysteresis / 2;
}
float distanceFromPlayer = Vector2.Distance(position, playerPosition);
if (distanceFromPlayer > chaseDistance)
{
aiState = AIState.Wander;
}
else
{
aiState = AIState.Chasing;
}
float currentSpeed;
if (aiState == AIState.Chasing)
{
orientation = TurnToFace(playerPosition, orientation, maxRotation);
currentSpeed = maxSpeed;
}
else if (aiState == AIState.Wander)
{
Wander();
}
}
public void Draw(SpriteBatch spriteBatch)
{
boundingBox.X = (int)position.X;
boundingBox.Y = (int)position.Y;
drawingOrigin = new Vector2(texture.Width / 2, texture.Height / 2);
spriteBatch.Draw(texture, boundingBox, null, Color.White, orientation, drawingOrigin, SpriteEffects.None, 0.0f);
}
public Vector2 PlayerPosition
{
set
{
playerPosition = value;
}
get
{
return playerPosition;
}
}
You get the distance from the player using:
float distanceFromPlayer = Vector2.Distance(position, playerPosition);
But you never actually set the variable playerPosition in your class. So effectively if the enemy is within the chase radius from the point (0,0) they will chase your player, but otherwise will they will just wander around.
I would recommend doing one of two things to solve this issue.
First off you could change the parameters of your Update method to take in the Vector2 of the players position.
A second approach (the one I would personally choose) would be to add a new field (class variable) that is of type Player and then in your Virtual_Aliens' constructor pass in an instance of the player class. That way any time you reference playerPosition you would be able to just say player.Position (or however you have your position field named).

Categories