Error in C # script in Unity. ImageEffects - c#

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.

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

Character is jittering after adding falling function

Let me just preface my question by saying I'm quite new to unity and programming as a whole. However I've been experimenting with some movement and after adding my falling function I've run into some trouble. Sometimes if I press play in Unity the character will start jittering quite heavy, every frame it also jumps between isInAir and isGrounded (as well as isInteracting). This causes my player to shake heavily and jitter forward as well.
Sometimes the falling animation will happen but my character falls really slowly, sometimes the animation doesn't work. Does anyone know how I can fix this?
Here is my PlayerLocomotion, the everything falling related is mentioned under HandleFalling.
using System.Collections.Generic;
using UnityEngine;
namespace FS
{
public class PlayerLocomotion : MonoBehaviour
{
PlayerManager playerManager;
Transform cameraObject;
InputHandler inputHandler;
public Vector3 moveDirection;
[HideInInspector]
public Transform myTransform;
[HideInInspector]
public AnimatorHandler animatorHandler;
public new Rigidbody rigidbody;
public GameObject normalCamera;
[Header("Ground & Air Detection Stats")]
[SerializeField]
float groundDetectionRayStartPoint = 0.5f;
[SerializeField]
float minimumDistanceNeededToBeginFall = 1f;
[SerializeField]
float groundDirectionRayDistance = 0.2f;
LayerMask ignoreForGroundCheck;
public float inAirTimer;
[Header("Movement Stats")]
[SerializeField]
float movementSpeed = 5;
[SerializeField]
float sprintSpeed = 7;
[SerializeField]
float rotationSpeed = 10;
[SerializeField]
float fallingSpeed = 45;
void Start()
{
playerManager = GetComponent<PlayerManager>();
rigidbody = GetComponent<Rigidbody>();
inputHandler = GetComponent<InputHandler>();
animatorHandler = GetComponentInChildren<AnimatorHandler>();
cameraObject = Camera.main.transform;
myTransform = transform;
animatorHandler.Initialize();
playerManager.isGrounded = true;
ignoreForGroundCheck = ~(1 << 10);
}
#region Movement
Vector3 normalVector;
Vector3 targetPosition;
private void HandleRotation(float delta)
{
Vector3 targetDir = Vector3.zero;
float moveOverride = inputHandler.moveAmount;
targetDir = cameraObject.forward * inputHandler.vertical;
targetDir += cameraObject.right * inputHandler.horizontal;
targetDir.Normalize();
targetDir.y = 0;
if (targetDir == Vector3.zero) targetDir = myTransform.forward;
float rs = rotationSpeed;
Quaternion tr = Quaternion.LookRotation(targetDir);
Quaternion targetRotation =
Quaternion.Slerp(myTransform.rotation, tr, rs * delta);
myTransform.rotation = targetRotation;
}
public void HandleMovement(float delta)
{
if (inputHandler.rollFlag) return;
if (playerManager.isInteracting) return;
moveDirection = cameraObject.forward * inputHandler.vertical;
moveDirection += cameraObject.right * inputHandler.horizontal;
moveDirection.Normalize();
moveDirection.y = 0;
float speed = movementSpeed;
if (inputHandler.sprintFlag)
{
speed = sprintSpeed;
playerManager.isSprinting = true;
moveDirection *= speed;
}
else
{
moveDirection *= speed;
}
Vector3 projectedVelocity =
Vector3.ProjectOnPlane(moveDirection, normalVector);
rigidbody.velocity = projectedVelocity;
animatorHandler
.UpdateAnimatorValues(inputHandler.moveAmount,
0,
playerManager.isSprinting);
if (animatorHandler.canRotate)
{
HandleRotation (delta);
}
}
public void HandleRollingAndSprinting(float delta)
{
if (animatorHandler.anim.GetBool("isInteracting")) return;
if (inputHandler.rollFlag)
{
moveDirection = cameraObject.forward * inputHandler.vertical;
moveDirection += cameraObject.right * inputHandler.horizontal;
if (inputHandler.moveAmount > 0)
{
animatorHandler.PlayTargetAnimation("Rolling", true);
moveDirection.y = 0;
Quaternion rollRotation =
Quaternion.LookRotation(moveDirection);
myTransform.rotation = rollRotation;
}
else
{
animatorHandler.PlayTargetAnimation("Backstep", true);
}
}
}
public void HandleFalling(float delta, Vector3 moveDirection)
{
playerManager.isGrounded = false;
RaycastHit hit;
Vector3 origin = myTransform.position;
origin.y += groundDetectionRayStartPoint;
if (Physics.Raycast(origin, myTransform.forward, out hit, 0.4f))
{
moveDirection = Vector3.zero;
}
if (playerManager.isInAir)
{
rigidbody.AddForce(-Vector3.up * fallingSpeed);
rigidbody.AddForce(moveDirection * fallingSpeed / 5f);
}
Vector3 dir = -moveDirection;
dir.Normalize();
origin = origin + dir * groundDirectionRayDistance;
targetPosition = myTransform.position;
Debug
.DrawRay(origin,
-Vector3.up * minimumDistanceNeededToBeginFall,
Color.red,
0.1f,
false);
if (Physics.Raycast(origin, -Vector3.up, out hit, minimumDistanceNeededToBeginFall, ignoreForGroundCheck))
{
normalVector = hit.normal;
Vector3 tp = hit.point;
playerManager.isGrounded = true;
targetPosition.y = tp.y;
if (playerManager.isInAir)
{
if (inAirTimer > 0.5f)
{
Debug.Log("You were in the air for " + inAirTimer);
animatorHandler.PlayTargetAnimation("Land", true);
inAirTimer = 0;
}
else
{
animatorHandler
.PlayTargetAnimation("Empty", false);
inAirTimer = 0;
}
playerManager.isInAir = false;
}
else
{
if (playerManager.isGrounded)
{
playerManager.isGrounded = false;
}
if (playerManager.isInAir == false)
{
if (playerManager.isInteracting == false)
{
animatorHandler
.PlayTargetAnimation("Falling", true);
}
Vector3 vel = rigidbody.velocity;
vel.Normalize();
rigidbody.velocity = vel * (movementSpeed / 2);
playerManager.isInAir = true;
}
}
if (playerManager.isInteracting || inputHandler.moveAmount > 0)
{
myTransform.position = Vector3.Lerp(myTransform.position, targetPosition, Time.deltaTime / 0.1f);
}
else
{
myTransform.position = targetPosition;
}
}
}
#endregion
}
}

Issue with transform.position

I am trying to make a simple pong game where once the player or the enemy scores both of them get repositioned on the field.
I have this script on the enemy:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehavior : MonoBehaviour
{
Vector3 ballPosition;
Vector3 paddlePosition;
float movementSpeed = 0.1f;
public Transform target;
public float maxAngle = 35.0f;
private Quaternion baseRotation;
private Quaternion targetRotation;
// Start is called before the first frame update
void Start()
{
baseRotation = transform.rotation;
}
// Update is called once per frame
void Update()
{
ballPosition = GameObject.Find("Ball").transform.position;
paddlePosition = this.transform.position;
if (paddlePosition.z < ballPosition.z)
{
paddlePosition.z += movementSpeed;
}
else if (paddlePosition.z > ballPosition.z)
{
paddlePosition.z -= movementSpeed;
}
transform.position = paddlePosition;
Vector3 look = target.transform.position - transform.position;
look.z = 0;
Quaternion q = Quaternion.LookRotation(look);
if (Quaternion.Angle(q, baseRotation) <= maxAngle)
{
targetRotation = q;
}
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
}
}
And then a goal script attached to the goal that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Goal : MonoBehaviour
{
public GameObject Ball;
public GameObject Player;
public GameObject Enemy;
public Text Player2Score;
public Text Player1Score;
int Player2ScoreText = 0;
int Player1ScoreText = 0;
Rigidbody ballrig;
Rigidbody playerrig;
Rigidbody enemyrig;
public ParticleSystem Particles;
float timeLeft = 1.0f;
public bool slowMo = false;
// Start is called before the first frame update
void Start()
{
ballrig = Ball.GetComponent<Rigidbody>();
playerrig = Player.GetComponent<Rigidbody>();
enemyrig = Enemy.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (slowMo == true)
{
timeLeft -= Time.deltaTime;
if (timeLeft < 0)
{
slowMo = false;
timeLeft = 1.0f;
Time.timeScale = 1f;
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.name == "Ball" && name == "Player_Goal")
{
slowMo = true;
Time.timeScale = 0.5f;
Explode();
Player2ScoreText += 1;
Player2Score.text = ("" + Player2ScoreText);
Ball.transform.position = new Vector3(0f, 4f, 0f);
Player.transform.position = new Vector3(-20f, 2f, 0f);
Enemy.transform.position = new Vector3(20f, 2f, 0f);
ballrig.velocity = Vector3.zero;
ballrig.angularVelocity = Vector3.zero;
playerrig.velocity = Vector3.zero;
playerrig.angularVelocity = Vector3.zero;
enemyrig.velocity = Vector3.zero;
enemyrig.angularVelocity = Vector3.zero;
int whoGetsIt = Random.Range(0, 2);
if (whoGetsIt >= 1)
{
Vector3 Impulse = new Vector3(-10f, 5f, Random.Range(-10f, 10f));
Ball.GetComponent<Rigidbody>().AddForce(Impulse, ForceMode.Impulse);
}
else
{
Vector3 Impulse = new Vector3(10f, 0f, Random.Range(-10f, 10f));
Ball.GetComponent<Rigidbody>().AddForce(Impulse, ForceMode.Impulse);
}
}
else if (other.name == "Ball" && name == "Enemy_Goal")
{
slowMo = true;
Time.timeScale = 0.5f;
Explode();
Player1ScoreText += 1;
Player1Score.text = ("" + Player1ScoreText);
Ball.transform.position = new Vector3(0f, 4f, 0f);
Player.transform.position = new Vector3(-20f, 2f, 0f);
Enemy.transform.position = new Vector3(20f, 2f, 0f);
ballrig.velocity = Vector3.zero;
ballrig.angularVelocity = Vector3.zero;
playerrig.velocity = Vector3.zero;
playerrig.angularVelocity = Vector3.zero;
enemyrig.velocity = Vector3.zero;
enemyrig.angularVelocity = Vector3.zero;
int whoGetsIt = Random.Range(0, 2);
if (whoGetsIt >= 1)
{
Vector3 Impulse = new Vector3(-10f, 5f, Random.Range(-10f, 10f));
Ball.GetComponent<Rigidbody>().AddForce(Impulse, ForceMode.Impulse);
}
else
{
Vector3 Impulse = new Vector3(10f, 0f, Random.Range(-10f, 10f));
Ball.GetComponent<Rigidbody>().AddForce(Impulse, ForceMode.Impulse);
}
}
}
void Explode()
{
Particles.Play();
}
}
Now the ball gets repositioned correctly after someone scores but for some reason the player and the enemy do not.
Is it because they both have code in their update function so that code "overwrights" the repositioned command? And if so how can I get around that?
I can see that your players are using Rigidbody or Rigidbody2D.
Whenever a rigidbody is involved you should not set any position via transform but rather use the according rigidbody methods like MovePosition and MoveRotation or for directly setting them go through Rigibody.position and Rigidbody.rotation e.g.
....
slowMo = true;
Time.timeScale = 0.5f;
Explode();
Player2ScoreText += 1;
Player2Score.text = ("" + Player2ScoreText);
Ball.GetComponent<Rigidbody>().position = new Vector3(0f, 4f, 0f);
Player.GetComponent<Rigidbody>().position = new Vector3(-20f, 2f, 0f);
Enemy.GetComponent<Rigidbody>().position = new Vector3(20f, 2f, 0f);
ballrig.velocity = Vector3.zero;
ballrig.angularVelocity = Vector3.zero;
playerrig.velocity = Vector3.zero;
playerrig.angularVelocity = Vector3.zero;
enemyrig.velocity = Vector3.zero;
enemyrig.angularVelocity = Vector3.zero;
int whoGetsIt = Random.Range(0, 2);
....
And then also in the EnemyBehaviour -> It should be FixedUpdate and look like
public Rigidbody target;
Rigidbody ball;
Rigidbody ownRigidbody;
void Start()
{
baseRotation = transform.rotation;
// Get reference only ONCE and store them1
ball = GameObject.Find("Ball").GetComponent<Rigidbody>();
ownRigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
ballPosition = ball.position;
paddlePosition = ownRigidbody.position;
if (paddlePosition.z < ballPosition.z)
{
paddlePosition.z += movementSpeed;
}
else if (paddlePosition.z > ballPosition.z)
{
paddlePosition.z -= movementSpeed;
}
ownRigidbody.MovePosition(paddlePosition;)
Vector3 look = target.position - ownRigidbody.position;
look.z = 0;
Quaternion q = Quaternion.LookRotation(look);
if (Quaternion.Angle(q, baseRotation) <= maxAngle)
{
targetRotation = q;
}
ownRigidbody.MoveRotation(Quaternion.Slerp(ownRigidbody.rotation, targetRotation, Time.deltaTime * 2.0f));
}
since here you want smooth interpolated position

Touch to Zoom And Rotate script for Unity player

I had this unity player embedded in android studio activity.
It is a 3d model with animation, which I would like viewer to be able to zoom and view in different angle.
Script are from this link
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MobilemaxCamera : MonoBehaviour {
public Transform target;
public Vector3 targetOffset;
public float distance = 5.0f;
public float maxDistance = 20;
public float minDistance = .6f;
public float xSpeed = 5.0f;
public float ySpeed = 5.0f;
public int yMinLimit = -80;
public int yMaxLimit = 80;
public float zoomRate = 10.0f;
public float panSpeed = 0.3f;
public float zoomDampening = 5.0f;
private float xDeg = 0.0f;
private float yDeg = 0.0f;
private float currentDistance;
private float desiredDistance;
private Quaternion currentRotation;
private Quaternion desiredRotation;
private Quaternion rotation;
private Vector3 position;
private Vector3 FirstPosition;
private Vector3 SecondPosition;
private Vector3 delta;
private Vector3 lastOffset;
private Vector3 lastOffsettemp;
//private Vector3 CameraPosition;
//private Vector3 Targetposition;
//private Vector3 MoveDistance;
void Start() { Init(); }
void OnEnable() { Init(); }
public void Init()
{
//If there is no target, create a temporary target at 'distance' from the cameras current viewpoint
if (!target)
{
GameObject go = new GameObject("Cam Target");
go.transform.position = transform.position + (transform.forward * distance);
target = go.transform;
}
distance = Vector3.Distance(transform.position, target.position);
currentDistance = distance;
desiredDistance = distance;
//be sure to grab the current rotations as starting points.
position = transform.position;
rotation = transform.rotation;
currentRotation = transform.rotation;
desiredRotation = transform.rotation;
xDeg = Vector3.Angle(Vector3.right, transform.right);
yDeg = Vector3.Angle(Vector3.up, transform.up);
}
/*
* Camera logic on LateUpdate to only update after all character movement logic has been handled.
*/
void LateUpdate()
{
// If Control and Alt and Middle button? ZOOM!
if (Input.touchCount==2)
{
Touch touchZero = Input.GetTouch (0);
Touch touchOne = Input.GetTouch (1);
Vector2 touchZeroPreviousPosition = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePreviousPosition = touchOne.position - touchOne.deltaPosition;
float prevTouchDeltaMag = (touchZeroPreviousPosition - touchOnePreviousPosition).magnitude;
float TouchDeltaMag = (touchZero.position - touchOne.position).magnitude;
float deltaMagDiff = prevTouchDeltaMag - TouchDeltaMag;
desiredDistance += deltaMagDiff * Time.deltaTime * zoomRate * 0.0025f * Mathf.Abs(desiredDistance);
}
// If middle mouse and left alt are selected? ORBIT
if (Input.touchCount==1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 touchposition = Input.GetTouch(0).deltaPosition;
xDeg += touchposition.x * xSpeed * 0.002f;
yDeg -= touchposition.y * ySpeed * 0.002f;
yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
}
desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
currentRotation = transform.rotation;
rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening);
transform.rotation = rotation;
if (Input.GetMouseButtonDown (1))
{
FirstPosition = Input.mousePosition;
lastOffset = targetOffset;
}
if (Input.GetMouseButton (1))
{
SecondPosition = Input.mousePosition;
delta = SecondPosition - FirstPosition;
targetOffset = lastOffset + transform.right * delta.x*0.003f + transform.up * delta.y*0.003f;
}
////////Orbit Position
// affect the desired Zoom distance if we roll the scrollwheel
desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance);
currentDistance = Mathf.Lerp(currentDistance, desiredDistance, Time.deltaTime * zoomDampening);
position = target.position - (rotation * Vector3.forward * currentDistance );
position = position - targetOffset;
transform.position = position;
}
private static float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
}
The zoom in and out work perfectly.
But the problem is, the rotate/pan is totally not working.
Anyone can give some help in this?
For the multi-touch, you have to use this script which I have given below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MultiTouch: MonoBehaviour
{
float initialFingersDistance;
Vector3 initialScale;
float rotationRate = 0.2f;
int direction = 1;
void LateUpdate()
{
if (Input.touches.Length == 1)
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Touch touch = Input.touches[0];
Quaternion desiredRotation = transform.rotation;
TouchLogic.Calculate();
if (Mathf.Abs(TouchLogic.turnAngleDelta) > 0)
{ // rotate
Vector3 rotationDeg = transform.eulerAngles;
rotationDeg.z = -TouchLogic.turnAngleDelta;
desiredRotation *= Quaternion.Euler(rotationDeg);
}
// not so sure those will work:
transform.rotation = desiredRotation;
// transform.Rotate(touch.deltaPosition.y * rotationRate, -touch.deltaPosition.x * rotationRate, 0, Space.World);
Vector3 rot = new Vector3(touch.deltaPosition.y * rotationRate, -touch.deltaPosition.x * rotationRate, transform.eulerAngles.z* rotationRate);
// transform.rotation = Quaternion.EulerAngles(rot);
}
}
else if (Input.touches.Length == 2)
{
Touch t1 = Input.touches[0];
Touch t2 = Input.touches[1];
if (t1.phase == TouchPhase.Began || t2.phase == TouchPhase.Began)
{
initialFingersDistance = Vector2.Distance(t1.position, t2.position);
initialScale = gameObject.transform.localScale;
}
else if (t1.phase == TouchPhase.Moved || t2.phase == TouchPhase.Moved)
{
var currentFingersDistance = Vector2.Distance(t1.position, t2.position);
// Debug.Log(currentFingersDistance);
////if (currentFingersDistance != initialFingersDistance)
//{
var scaleFactor = currentFingersDistance / initialFingersDistance;
gameObject.transform.localScale = initialScale * scaleFactor;
//}
float Dx = t1.position.x - transform.position.x;
float Dy = t1.position.y - transform.position.y;
//var cameraTransform = Camera.main.transform.InverseTransformPoint(0, 0, 0);
//transform.position = Camera.main.ScreenToWorldPoint(new Vector3(t2.position.x, t2.position.y, cameraTransform.z -0.5f));
Vector3 pos = t2.position;
//Vector3 pos = t1.position - t2.position;
Vector3 touchedPos = Camera.main.ScreenToWorldPoint(new Vector3(pos.x, pos.y, 10));
transform.position = Vector3.Lerp(transform.position, touchedPos, Time.deltaTime * 4);
// transform.position += touchedPos;
float pinchAmount = 0;
Quaternion desiredRotation = transform.rotation;
TouchLogic.Calculate();
if (Mathf.Abs(TouchLogic.pinchDistanceDelta) > 0)
{ // zoom
pinchAmount = TouchLogic.pinchDistanceDelta;
}
if (Mathf.Abs(TouchLogic.turnAngleDelta) > 0)
{ // rotate
Vector3 rotationDeg = Vector3.zero;
rotationDeg.z = -TouchLogic.turnAngleDelta;
desiredRotation *= Quaternion.Euler(rotationDeg);
}
// not so sure those will work:
transform.rotation = desiredRotation;
transform.position += Vector3.forward * pinchAmount;
}
}
}
}
For your touch control logic, you have to use this second script which I gave below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchLogic: MonoBehaviour
{
const float pinchTurnRatio = Mathf.PI / 2;
const float minTurnAngle = 0;
const float pinchRatio = 1;
const float minPinchDistance = 0;
const float panRatio = 1;
const float minPanDistance = 0;
/// <summary>
/// The delta of the angle between two touch points
/// </summary>
static public float turnAngleDelta;
/// <summary>
/// The angle between two touch points
/// </summary>
static public float turnAngle;
/// <summary>
/// The delta of the distance between two touch points that were distancing from each other
/// </summary>
static public float pinchDistanceDelta;
/// <summary>
/// The distance between two touch points that were distancing from each other
/// </summary>
static public float pinchDistance;
/// <summary>
/// Calculates Pinch and Turn - This should be used inside LateUpdate
/// </summary>
///
static public Touch LastTouch;
static public void Calculate()
{
pinchDistance = pinchDistanceDelta = 0;
turnAngle = turnAngleDelta = 0;
// if two fingers are touching the screen at the same time ...
if (Input.touchCount == 1)
{
Touch touch1 = Input.touches[0];
turnAngle = Angle(touch1.position, LastTouch.position);
float prevTurn = Angle(touch1.position + touch1.deltaPosition,
LastTouch.deltaPosition + LastTouch.position);
turnAngleDelta = Mathf.DeltaAngle(prevTurn, turnAngle);
// ... if it's greater than a minimum threshold, it's a turn!
if (Mathf.Abs(turnAngleDelta) > minTurnAngle)
{
turnAngleDelta *= pinchTurnRatio;
}
else
{
turnAngle = turnAngleDelta = 0;
}
LastTouch =Input.touches[0];
}
else if (Input.touchCount == 2)
{
Touch touch1 = Input.touches[0];
Touch touch2 = Input.touches[1];
// ... if at least one of them moved ...
if (touch1.phase == TouchPhase.Moved || touch2.phase == TouchPhase.Moved)
{
// ... check the delta distance between them ...
pinchDistance = Vector2.Distance(touch1.position, touch2.position);
float prevDistance = Vector2.Distance(touch1.position - touch1.deltaPosition,
touch2.position - touch2.deltaPosition);
pinchDistanceDelta = pinchDistance - prevDistance;
// ... if it's greater than a minimum threshold, it's a pinch!
if (Mathf.Abs(pinchDistanceDelta) > minPinchDistance)
{
pinchDistanceDelta *= pinchRatio;
}
else
{
pinchDistance = pinchDistanceDelta = 0;
}
// ... or check the delta angle between them ...
turnAngle = Angle(touch1.position, touch2.position);
float prevTurn = Angle(touch1.position + touch1.deltaPosition,
touch2.position + touch2.deltaPosition);
turnAngleDelta = Mathf.DeltaAngle(prevTurn, turnAngle);
// ... if it's greater than a minimum threshold, it's a turn!
if (Mathf.Abs(turnAngleDelta) > minTurnAngle)
{
turnAngleDelta *= pinchTurnRatio;
}
else
{
turnAngle = turnAngleDelta = 0;
}
}
}
}
static private float Angle(Vector2 pos1, Vector2 pos2)
{
Vector2 from = pos2 - pos1;
Vector2 to = new Vector2(1, 0);
float result = Vector2.Angle(from, to);
Vector3 cross = Vector3.Cross(from, to);
if (cross.z > 0)
{
result = 360f - result;
}
return result;
}
}
Both scripts are used in a single project. using these scripts you can easily rotate your 3d object.
Note: Please attach this both script in a single 3d object, so you can use this script easily.

Adding Android Mobile Controller to Unity Game

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.

Categories