Unity MouseLook script will not rotate on the X axis - c#

I am working on a Unity PlayerLook script and as soon as I enable the vertical rotation code I can look vertically, but my side to side motion is locked, with the camera only jittering. Disabling the vertical rotation code allows my camera to look horizontally.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}

If you are making an FPS game I was working on one not too long ago and got a solution like, create a new script and put it in the main camera, then in unity drag and drop your player object to the Player Body component on the Main Camera Script that you just created (Keep note that the script name must be named "MouseDir" for it to work):
I don't know why the Mouse X does not work I had the same problem awhile ago.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseDir : MonoBehaviour
{
public Transform playerBody;
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
float rotationY = 0F;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void LateUpdate()
{
transform.position = playerBody.transform.position;
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
playerBody.localEulerAngles = new Vector3(0, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
playerBody.Rotate(0, Input.GetAxis("Mouse X ") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
}

I got the mouselook and movement to work with this script I found online:
https://github.com/TheBozzz34/PR-Terrain-Multiplayer/blob/main/Assets/FirstPersion%20AIO%20Pack/FirstPersonAIO/FirstPersonAIO.cs
private void Update(){
#region Look Settings - Update
if(enableCameraMovement && !controllerPauseState){
float mouseYInput = 0;
float mouseXInput = 0;
float camFOV = playerCamera.fieldOfView;
if (cameraInputMethod == CameraInputMethod.Traditional || cameraInputMethod == CameraInputMethod.TraditionalWithConstraints){
mouseYInput = mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.X ? Input.GetAxis("Mouse Y") : -Input.GetAxis("Mouse Y");
mouseXInput = mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.Y ? Input.GetAxis("Mouse X") : -Input.GetAxis("Mouse X");
}
else{
mouseXInput= Input.GetAxis("Horizontal") * (mouseInputInversion == InvertMouseInput.None || mouseInputInversion == InvertMouseInput.Y ? 1 : -1);
} if(targetAngles.y > 180) { targetAngles.y -= 360; followAngles.y -= 360; } else if(targetAngles.y < -180) { targetAngles.y += 360; followAngles.y += 360; }
if(targetAngles.x > 180) { targetAngles.x -= 360; followAngles.x -= 360; } else if(targetAngles.x < -180) { targetAngles.x += 360; followAngles.x += 360; }
targetAngles.y += mouseXInput * (mouseSensitivity - ((baseCamFOV-camFOV)*fOVToMouseSensitivity)/6f);
if (cameraInputMethod == CameraInputMethod.Traditional){ targetAngles.x += mouseYInput * (mouseSensitivity - ((baseCamFOV - camFOV) * fOVToMouseSensitivity) / 6f);}
else {targetAngles.x = 0f;}
targetAngles.x = Mathf.Clamp(targetAngles.x, -0.5f * verticalRotationRange, 0.5f * verticalRotationRange);
followAngles = Vector3.SmoothDamp(followAngles, targetAngles, ref followVelocity, (cameraSmoothing)/100);
playerCamera.transform.localRotation = Quaternion.Euler(-followAngles.x + originalRotation.x,0,0);
transform.localRotation = Quaternion.Euler(0, followAngles.y+originalRotation.y, 0);
}
#endregion
#region Input Settings - Update
if(canHoldJump ? (canJump && Input.GetButton("Jump")) : (Input.GetButtonDown("Jump") && canJump) ){
jumpInput = true;
}else if(Input.GetButtonUp("Jump")){jumpInput = false;}
if(_crouchModifiers.useCrouch){
if(!_crouchModifiers.toggleCrouch){ isCrouching = _crouchModifiers.crouchOverride || Input.GetKey(_crouchModifiers.crouchKey);}
else if(Input.GetKeyDown(_crouchModifiers.crouchKey)){isCrouching = !isCrouching || _crouchModifiers.crouchOverride;}
}
if(Input.GetButtonDown("Cancel")){ControllerPause();}
#endregion
#region Movement Settings - Update
#endregion
#region Headbobbing Settings - Update
#endregion
}
private void FixedUpdate(){
#region Look Settings - FixedUpdate
#endregion
#region Movement Settings - FixedUpdate
if(useStamina){
isSprinting = Input.GetKey(sprintKey) && !isCrouching && staminaInternal > 0 && (Mathf.Abs(fps_Rigidbody.velocity.x) > 0.01f || Mathf.Abs(fps_Rigidbody.velocity.z) > 0.01f);
if(isSprinting){
staminaInternal -= (staminaDepletionSpeed*2)*Time.deltaTime;
if(drawStaminaMeter){
StaminaMeterBG.color = Vector4.MoveTowards(StaminaMeterBG.color, new Vector4(0,0,0,0.5f),0.15f);
StaminaMeter.color = Vector4.MoveTowards(StaminaMeter.color, new Vector4(1,1,1,1),0.15f);
}
}else if((!Input.GetKey(sprintKey)||Mathf.Abs(fps_Rigidbody.velocity.x)< 0.01f || Mathf.Abs(fps_Rigidbody.velocity.z)< 0.01f || isCrouching)&&staminaInternal<staminaLevel){
staminaInternal += staminaDepletionSpeed*Time.deltaTime;
}
if(drawStaminaMeter){
if(staminaInternal==staminaLevel){ StaminaMeterBG.color = Vector4.MoveTowards(StaminaMeterBG.color, new Vector4(0,0,0,0),0.15f);
StaminaMeter.color = Vector4.MoveTowards(StaminaMeter.color, new Vector4(1,1,1,0),0.15f);}
float x = Mathf.Clamp(Mathf.SmoothDamp(StaminaMeter.transform.localScale.x,(staminaInternal/staminaLevel)*StaminaMeterBG.transform.localScale.x,ref smoothRef,(1)*Time.deltaTime,1),0.001f, StaminaMeterBG.transform.localScale.x);
StaminaMeter.transform.localScale = new Vector3(x,1,1);
}
staminaInternal = Mathf.Clamp(staminaInternal,0,staminaLevel);
} else{isSprinting = Input.GetKey(sprintKey);}
Vector3 MoveDirection = Vector3.zero;
speed = walkByDefault ? isCrouching ? walkSpeedInternal : (isSprinting ? sprintSpeedInternal : walkSpeedInternal) : (isSprinting ? walkSpeedInternal : sprintSpeedInternal);
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingUpright && advanced.isTouchingWalkable){
MoveDirection = (transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal);
if(!didJump){fps_Rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;}
}
else if(advanced.isTouchingUpright && !advanced.isTouchingWalkable){
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
}
else{
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
MoveDirection = ((transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal) * (fps_Rigidbody.velocity.y>0.01f ? SlopeCheck() : 0.8f));
}
}
else{
MoveDirection = (transform.forward * inputXY.y * speed + transform.right * inputXY.x * walkSpeedInternal);
}
#region step logic
RaycastHit WT;
if(advanced.maxStepHeight > 0 && Physics.Raycast(transform.position - new Vector3(0,((capsule.height/2)*transform.localScale.y)-0.01f,0),MoveDirection,out WT,capsule.radius+0.15f,Physics.AllLayers,QueryTriggerInteraction.Ignore) && Vector3.Angle(WT.normal, Vector3.up)>88){
RaycastHit ST;
if(!Physics.Raycast(transform.position - new Vector3(0,((capsule.height/2)*transform.localScale.y)-(advanced.maxStepHeight),0),MoveDirection,out ST,capsule.radius+0.25f,Physics.AllLayers,QueryTriggerInteraction.Ignore)){
advanced.stairMiniHop = true;
transform.position += new Vector3(0,advanced.maxStepHeight*1.2f,0);
}
}
Debug.DrawRay(transform.position, MoveDirection,Color.red,0,false);
#endregion
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
inputXY = new Vector2(horizontalInput, verticalInput);
if(inputXY.magnitude > 1) { inputXY.Normalize(); }
#region Jump
yVelocity = fps_Rigidbody.velocity.y;
if(IsGrounded && jumpInput && jumpPowerInternal > 0 && !didJump){
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingFlat || advanced.isTouchingWalkable){
didJump=true;
jumpInput=false;
yVelocity += fps_Rigidbody.velocity.y<0.01f? jumpPowerInternal : jumpPowerInternal/3;
advanced.isTouchingWalkable = false;
advanced.isTouchingFlat = false;
advanced.isTouchingUpright = false;
fps_Rigidbody.constraints = RigidbodyConstraints.None | RigidbodyConstraints.FreezeRotation;
}
}else{
didJump=true;
jumpInput=false;
yVelocity += jumpPowerInternal;
}
}
if(advanced.maxSlopeAngle>0){
if(!didJump && advanced.lastKnownSlopeAngle>5 && advanced.isTouchingWalkable){
yVelocity *= SlopeCheck()/4;
}
if(advanced.isTouchingUpright && !advanced.isTouchingWalkable && !didJump){
yVelocity += Physics.gravity.y;
}
}
#endregion
if(playerCanMove && !controllerPauseState){
fps_Rigidbody.velocity = MoveDirection+(Vector3.up * yVelocity);
} else{fps_Rigidbody.velocity = Vector3.zero;}
if(inputXY.magnitude > 0 || !IsGrounded) {
capsule.sharedMaterial = advanced.zeroFrictionMaterial;
} else { capsule.sharedMaterial = advanced.highFrictionMaterial; }
fps_Rigidbody.AddForce(Physics.gravity * (advanced.gravityMultiplier - 1));
if(advanced.FOVKickAmount>0){
if(isSprinting && !isCrouching && playerCamera.fieldOfView != (baseCamFOV+(advanced.FOVKickAmount*2)-0.01f)){
if(Mathf.Abs(fps_Rigidbody.velocity.x)> 0.5f || Mathf.Abs(fps_Rigidbody.velocity.z)> 0.5f){
playerCamera.fieldOfView = Mathf.SmoothDamp(playerCamera.fieldOfView,baseCamFOV+(advanced.FOVKickAmount*2),ref advanced.fovRef,advanced.changeTime);
}
}
else if(playerCamera.fieldOfView != baseCamFOV){ playerCamera.fieldOfView = Mathf.SmoothDamp(playerCamera.fieldOfView,baseCamFOV,ref advanced.fovRef,advanced.changeTime*0.5f);}
}
if(_crouchModifiers.useCrouch) {
if(isCrouching) {
capsule.height = Mathf.MoveTowards(capsule.height, _crouchModifiers.colliderHeight/1.5f, 5*Time.deltaTime);
walkSpeedInternal = walkSpeed*_crouchModifiers.crouchWalkSpeedMultiplier;
jumpPowerInternal = jumpPower* _crouchModifiers.crouchJumpPowerMultiplier;
} else {
capsule.height = Mathf.MoveTowards(capsule.height, _crouchModifiers.colliderHeight, 5*Time.deltaTime);
walkSpeedInternal = walkSpeed;
sprintSpeedInternal = sprintSpeed;
jumpPowerInternal = jumpPower;
}
}
#endregion
#region Headbobbing Settings - FixedUpdate
float yPos = 0;
float xPos = 0;
float zTilt = 0;
float xTilt = 0;
float bobSwayFactor = 0;
float bobFactor = 0;
float strideLangthen = 0;
float flatVel = 0;
//calculate headbob freq
if(useHeadbob == true || enableAudioSFX){
Vector3 vel = (fps_Rigidbody.position - previousPosition) / Time.deltaTime;
Vector3 velChange = vel - previousVelocity;
previousPosition = fps_Rigidbody.position;
previousVelocity = vel;
springVelocity -= velChange.y;
springVelocity -= springPosition * springElastic;
springVelocity *= springDampen;
springPosition += springVelocity * Time.deltaTime;
springPosition = Mathf.Clamp(springPosition, -0.3f, 0.3f);
if(Mathf.Abs(springVelocity) < springVelocityThreshold && Mathf.Abs(springPosition) < springPositionThreshold) { springPosition = 0; springVelocity = 0; }
flatVel = new Vector3(vel.x, 0.0f, vel.z).magnitude;
strideLangthen = 1 + (flatVel * ((headbobFrequency*2)/10));
headbobCycle += (flatVel / strideLangthen) * (Time.deltaTime / headbobFrequency);
bobFactor = Mathf.Sin(headbobCycle * Mathf.PI * 2);
bobSwayFactor = Mathf.Sin(Mathf.PI * (2 * headbobCycle + 0.5f));
bobFactor = 1 - (bobFactor * 0.5f + 1);
bobFactor *= bobFactor;
yPos = 0;
xPos = 0;
zTilt = 0;
if(jumpLandIntensity>0 && !advanced.stairMiniHop){xTilt = -springPosition * (jumpLandIntensity*5.5f);}
else if(!advanced.stairMiniHop){xTilt = -springPosition;}
if(IsGrounded){
if(new Vector3(vel.x, 0.0f, vel.z).magnitude < 0.1f) { headbobFade = Mathf.MoveTowards(headbobFade, 0.0f,0.5f); } else { headbobFade = Mathf.MoveTowards(headbobFade, 1.0f, Time.deltaTime); }
float speedHeightFactor = 1 + (flatVel * 0.3f);
xPos = -(headbobSideMovement/10) * headbobFade *bobSwayFactor;
yPos = springPosition * (jumpLandIntensity/10) + bobFactor * (headbobHeight/10) * headbobFade * speedHeightFactor;
zTilt = bobSwayFactor * (headbobSwayAngle/10) * headbobFade;
}
}
//apply headbob position
if(useHeadbob == true){
if(fps_Rigidbody.velocity.magnitude >0.1f){
head.localPosition = Vector3.MoveTowards(head.localPosition, snapHeadjointToCapsul ? (new Vector3(originalLocalPosition.x,(capsule.height/2)*head.localScale.y,originalLocalPosition.z) + new Vector3(xPos, yPos, 0)) : originalLocalPosition + new Vector3(xPos, yPos, 0),0.5f);
}else{
head.localPosition = Vector3.SmoothDamp(head.localPosition, snapHeadjointToCapsul ? (new Vector3(originalLocalPosition.x,(capsule.height/2)*head.localScale.y,originalLocalPosition.z) + new Vector3(xPos, yPos, 0)) : originalLocalPosition + new Vector3(xPos, yPos, 0),ref miscRefVel, 0.15f);
}
head.localRotation = Quaternion.Euler(xTilt, 0, zTilt);
}
#endregion
#region Dynamic Footsteps
if(enableAudioSFX){
if(fsmode == FSMode.Dynamic)
{
RaycastHit hit = new RaycastHit();
if(Physics.Raycast(transform.position, Vector3.down, out hit)){
if(dynamicFootstep.materialMode == DynamicFootStep.matMode.physicMaterial){
dynamicFootstep.currentClipSet = (dynamicFootstep.woodPhysMat.Any() && dynamicFootstep.woodPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.woodClipSet.Any()) ? // If standing on Wood
dynamicFootstep.woodClipSet : ((dynamicFootstep.grassPhysMat.Any() && dynamicFootstep.grassPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.grassClipSet.Any()) ? // If standing on Grass
dynamicFootstep.grassClipSet : ((dynamicFootstep.metalAndGlassPhysMat.Any() && dynamicFootstep.metalAndGlassPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.metalAndGlassClipSet.Any()) ? // If standing on Metal/Glass
dynamicFootstep.metalAndGlassClipSet : ((dynamicFootstep.rockAndConcretePhysMat.Any() && dynamicFootstep.rockAndConcretePhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.rockAndConcreteClipSet.Any()) ? // If standing on Rock/Concrete
dynamicFootstep.rockAndConcreteClipSet : ((dynamicFootstep.dirtAndGravelPhysMat.Any() && dynamicFootstep.dirtAndGravelPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.dirtAndGravelClipSet.Any()) ? // If standing on Dirt/Gravle
dynamicFootstep.dirtAndGravelClipSet : ((dynamicFootstep.mudPhysMat.Any() && dynamicFootstep.mudPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.mudClipSet.Any())? // If standing on Mud
dynamicFootstep.mudClipSet : ((dynamicFootstep.customPhysMat.Any() && dynamicFootstep.customPhysMat.Contains(hit.collider.sharedMaterial) && dynamicFootstep.customClipSet.Any())? // If standing on the custom material
dynamicFootstep.customClipSet : footStepSounds)))))); // If material is unknown, fall back
}else if (hit.collider.GetComponent<MeshRenderer>()){
dynamicFootstep.currentClipSet = (dynamicFootstep.woodMat.Any() && dynamicFootstep.woodMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.woodClipSet.Any()) ? // If standing on Wood
dynamicFootstep.woodClipSet : ((dynamicFootstep.grassMat.Any() && dynamicFootstep.grassMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.grassClipSet.Any()) ? // If standing on Grass
dynamicFootstep.grassClipSet : ((dynamicFootstep.metalAndGlassMat.Any() && dynamicFootstep.metalAndGlassMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.metalAndGlassClipSet.Any()) ? // If standing on Metal/Glass
dynamicFootstep.metalAndGlassClipSet : ((dynamicFootstep.rockAndConcreteMat.Any() && dynamicFootstep.rockAndConcreteMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.rockAndConcreteClipSet.Any()) ? // If standing on Rock/Concrete
dynamicFootstep.rockAndConcreteClipSet : ((dynamicFootstep.dirtAndGravelMat.Any() && dynamicFootstep.dirtAndGravelMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.dirtAndGravelClipSet.Any()) ? // If standing on Dirt/Gravle
dynamicFootstep.dirtAndGravelClipSet : ((dynamicFootstep.mudMat.Any() && dynamicFootstep.mudMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.mudClipSet.Any())? // If standing on Mud
dynamicFootstep.mudClipSet : ((dynamicFootstep.customMat.Any() && dynamicFootstep.customMat.Contains(hit.collider.GetComponent<MeshRenderer>().sharedMaterial) && dynamicFootstep.customClipSet.Any())? // If standing on the custom material
dynamicFootstep.customClipSet : footStepSounds.Any() ? footStepSounds : null)))))); // If material is unknown, fall back
}
if(IsGrounded)
{
if(!previousGrounded)
{
if(dynamicFootstep.currentClipSet.Any()) { audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
if(dynamicFootstep.currentClipSet.Any()){ audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(dynamicFootstep.currentClipSet.Any()){ audioSource.PlayOneShot(dynamicFootstep.currentClipSet[Random.Range(0, dynamicFootstep.currentClipSet.Count)],Volume/10); }
}
previousGrounded = false;
}
} else {
dynamicFootstep.currentClipSet = footStepSounds;
if(IsGrounded)
{
if(!previousGrounded)
{
if(landSound){ audioSource.PlayOneShot(landSound,Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
int n = Random.Range(0, footStepSounds.Count);
if(footStepSounds.Any()){ audioSource.PlayOneShot(footStepSounds[n],Volume/10); }
footStepSounds[n] = footStepSounds[0];
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(jumpSound){ audioSource.PlayOneShot(jumpSound,Volume/10); }
}
previousGrounded = false;
}
}
} else
{
if(IsGrounded)
{
if(!previousGrounded)
{
if(landSound) { audioSource.PlayOneShot(landSound,Volume/10); }
nextStepTime = headbobCycle + 0.5f;
} else
{
if(headbobCycle > nextStepTime)
{
nextStepTime = headbobCycle + 0.5f;
int n = Random.Range(0, footStepSounds.Count);
if(footStepSounds.Any() && footStepSounds[n] != null){ audioSource.PlayOneShot(footStepSounds[n],Volume/10);}
}
}
previousGrounded = true;
} else
{
if(previousGrounded)
{
if(jumpSound) { audioSource.PlayOneShot(jumpSound,Volume/10); }
}
previousGrounded = false;
}
}
}
#endregion
#region Reset Checks
IsGrounded = false;
if(advanced.maxSlopeAngle>0){
if(advanced.isTouchingFlat || advanced.isTouchingWalkable || advanced.isTouchingUpright){didJump = false;}
advanced.isTouchingWalkable = false;
advanced.isTouchingUpright = false;
advanced.isTouchingFlat = false;
}
#endregion
}

Related

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

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

Unity jump issue

I make 3rd person game, where i have script for control model of my character.
Problem is that when i jump and don't push any button he stack in the air, but if i jump with pushing controlling button he worked normally.
Thanks in advance.
Player controller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class RelativeMovement : MonoBehaviour
{
[SerializeField] private Transform target;
public float rotSpeed = 5.0f;
public float moveSpeed = 6.0f;
public float jumpSpeed = 15.0f;
public float gravity = -9.8f;
public float terminalVelocity = -20.0f;
public float minFall = -1.5f;
private float _vertSpeed;
private CharacterController _charController;
private ControllerColliderHit _contact;
void Start()
{
_vertSpeed = minFall;
_charController = GetComponent<CharacterController>();
}
void Update()
{
Vector3 movement = Vector3.zero;
float horInput = Input.GetAxis("Horizontal");
float vertInput = Input.GetAxis("Vertical");
if(horInput != 0 || vertInput != 0)
{
movement.x = horInput * moveSpeed;
movement.z = vertInput * moveSpeed;
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y, 0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
bool hitGround = false;
RaycastHit hit;
if(_vertSpeed < 0 && Physics.Raycast(transform.position, Vector3.down, out hit))
{
float check =
(_charController.height + _charController.radius) / 1.9f;
hitGround = hit.distance <= check;
}
if(hitGround)
{
if (Input.GetButtonDown("Jump"))
{
_vertSpeed = jumpSpeed;
}
else
{
_vertSpeed = minFall;
}
}
else
{
_vertSpeed += gravity * 5 * Time.deltaTime;
if(_vertSpeed < terminalVelocity)
{
_vertSpeed = terminalVelocity;
}
if(_charController.isGrounded)
{
if(Vector3.Dot(movement, _contact.normal) < 0)
{
movement = _contact.normal * moveSpeed;
}
else
{
movement += _contact.normal * moveSpeed;
}
}
}
movement.y = _vertSpeed;
movement *= Time.deltaTime;
_charController.Move(movement);
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
_contact = hit;
}
}
Jesus photo:
enter image description here
I didn't go through all of the code but I can immediately see what can cause the problem you describe:
your entire logic happen under this if statement:
if(horInput != 0 || vertInput != 0)
So everything inside this logic block will happen only when you actively press a movement button.
You can remove it (or better yet, close the if block at the right spot.. I think it would be 2 lines down)
The answer of this question is:
if((horInput == 0 || vertInput == 0) || (horInput != 0 && vertInput != 0))
{
movement.x = horInput * moveSpeed;
movement.z = vertInput * moveSpeed;
if(horInput != 0 || vertInput != 0)
{
movement = Vector3.ClampMagnitude(movement, moveSpeed);
Quaternion tmp = target.rotation;
target.eulerAngles = new Vector3(0, target.eulerAngles.y, 0);
movement = target.TransformDirection(movement);
target.rotation = tmp;
Quaternion direction = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Lerp(transform.rotation,
direction, rotSpeed * Time.deltaTime);
}
Thanks Joe

How to set an initial value for UI_Knob?

I am trying to set an initial value for UI.Extensions UI_Knob
see link to UI.Extensions repo UI.Extensions bitbutcket
Through some searching I have found maybe the best way to set an initial value is to use simulated pointerEventData and pass it to the script using ExecuteEvents, since the UI_Knob script uses the mouse position to set it's value.
--BELOW IS THE CODE FOR THE UI_Knob--
/// Credit Tomasz Schelenz
/// Sourced from - https://bitbucket.org/ddreaper/unity-ui-
//ONLY ALLOW ROTATION WITH POINTER OVER THE CONTROL
public void OnPointerDown(PointerEventData eventData)
{
_canDrag = true;
}
public void OnPointerUp(PointerEventData eventData)
{
_canDrag = false;
}
public void OnPointerEnter(PointerEventData eventData)
{
_canDrag = true;
}
public void OnPointerExit(PointerEventData eventData)
{
_canDrag = true; // Now you can drag with pointer OFF control.
}
public void OnBeginDrag(PointerEventData eventData)
{
SetInitPointerData(eventData);
}
void SetInitPointerData(PointerEventData eventData)
{
_initRotation = transform.rotation;
_currentVector = eventData.position - (Vector2)transform.position;
_initAngle = Mathf.Atan2(_currentVector.y, _currentVector.x) * Mathf.Rad2Deg;
}
public void OnDrag(PointerEventData eventData)
{
//CHECK IF CAN DRAG
if (!_canDrag)
{
SetInitPointerData(eventData);
return;
}
_currentVector = eventData.position - (Vector2)transform.position;
_currentAngle = Mathf.Atan2(_currentVector.y, _currentVector.x) * Mathf.Rad2Deg;
Quaternion addRotation = Quaternion.AngleAxis(_currentAngle - _initAngle, this.transform.forward);
addRotation.eulerAngles = new Vector3(0, 0, addRotation.eulerAngles.z);
Quaternion finalRotation = _initRotation * addRotation;
if (direction == Direction.CW)
{
knobValue = 1 - (finalRotation.eulerAngles.z / 360f);
if (snapToPosition)
{
SnapToPosition(ref knobValue);
finalRotation.eulerAngles = new Vector3(0, 0, 360 - 360 * knobValue);
}
}
else
{
knobValue = (finalRotation.eulerAngles.z / 360f);
if (snapToPosition)
{
SnapToPosition(ref knobValue);
finalRotation.eulerAngles = new Vector3(0, 0, 360 * knobValue);
}
}
//PREVENT OVERROTATION
if (Mathf.Abs(knobValue - _previousValue) > 0.5f)
{
if (knobValue < 0.5f && loops > 1 && _currentLoops < loops - 1)
{
_currentLoops++;
}
else if (knobValue > 0.5f && _currentLoops >= 1)
{
_currentLoops--;
}
else
{
if (knobValue > 0.5f && _currentLoops == 0)
{
knobValue = 0;
transform.localEulerAngles = Vector3.zero;
SetInitPointerData(eventData);
InvokeEvents(knobValue + _currentLoops);
return;
}
else if (knobValue < 0.5f && _currentLoops == loops - 1)
{
knobValue = 1;
transform.localEulerAngles = Vector3.zero;
SetInitPointerData(eventData);
InvokeEvents(knobValue + _currentLoops);
return;
}
}
}
//CHECK MAX VALUE
if (maxValue > 0)
{
if (knobValue + _currentLoops > maxValue)
{
knobValue = maxValue;
float maxAngle = direction == Direction.CW ? 360f - 360f * maxValue : 360f * maxValue;
transform.localEulerAngles = new Vector3(0, 0, maxAngle);
SetInitPointerData(eventData);
InvokeEvents(knobValue);
return;
}
}
transform.rotation = finalRotation;
InvokeEvents(knobValue + _currentLoops);
_previousValue = knobValue;
}
private void SnapToPosition(ref float knobValue)
{
float snapStep = 1 / (float)snapStepsPerLoop;
float newValue = Mathf.Round(knobValue / snapStep) * snapStep;
knobValue = newValue;
}
private void InvokeEvents(float value)
{
if (clampOutput01)
value /= loops;
OnValueChanged.Invoke(value);
}
}
[System.Serializable]
public class KnobFloatValueEvent : UnityEvent<float> { }
}
I Answered my own question without using simulated mouse data. Instead, I added a Start() method with MyStartingAngle() method. See below. I chopped up the UI_Knob's method for rotation/setting value and basically just injected my own angle. I would still like to know how to perform this with simulated mouse data if anyone is willing. I would appreciate any input on my solution as well. Thanks for reading!!
// ADD THIS INTO UI_Knob script below initialization.
// I added this here to allow for setting an initial rotation/value.
void Start(){
float myFirstAngle = 180f;
MyStartingAngle (myFirstAngle);
}
void MyStartingAngle(float angle){
_initRotation = transform.rotation;
Quaternion addRotation = Quaternion.AngleAxis(angle, this.transform.forward);
addRotation.eulerAngles = new Vector3(0, 0, addRotation.eulerAngles.z);
Quaternion finalRotation = _initRotation * addRotation;
knobValue = 1 - (finalRotation.eulerAngles.z / 360f);
transform.rotation = finalRotation;
InvokeEvents(knobValue + _currentLoops);
_previousValue = knobValue;
}

Unity - OnTriggerEnter bullet ricochet

i have some problems with simple ballistics.As i am new to coding and i wasted 2 days with searching, i decided to ask a question. I have a problem with my bullet.cs script, code works fine, except ricochet part. I used OnTriggerEnter beacuse bullets will penetrate different materials, but will bounce under specific angles, so i used collider as a trigger only. I know it can be dobe using OnCollisionEnter to determine normal and use Vector3.Reflect. But if collider is not set as a trigger only, bullets will be bouncing off from everithing a will never penetrate a wall. Just need a help with ricochet part on the bottom.
public Rigidbody rb;
private float vel;
private float kEnergy;
private bool AP = false;
private bool HP = false;
private bool ricochet = false;
// Use this for initialization
void Start () {
vel = 738f;
kEnergy = 2108f;
//HP == false;
Destroy (gameObject, 10);
rb = GetComponent<Rigidbody> ();
rb.velocity = transform.forward * vel;
Quaternion bulletRotaion = transform.rotation;
Debug.Log (bulletRotaion.eulerAngles);
}
// Update is called once per frame
void Update () {
float curVelocity = rb.velocity.magnitude;
if (curVelocity <= 0)
{
curVelocity = 0f;
}
}
void OnTriggerEnter (Collider c)
{
if (c.tag == "Wall") {
Quaternion localOffset = transform.rotation;
float impactAngleX = c.gameObject.GetComponent <MaterialDensity> ().angleX;
float impactAngleY = c.gameObject.GetComponent <MaterialDensity> ().angleY;
float impactAngleZ = c.gameObject.GetComponent <MaterialDensity> ().angleZ;
float angleX = localOffset.eulerAngles.x;
float angleY = localOffset.eulerAngles.y;
float angleZ = localOffset.eulerAngles.z;
float density = c.gameObject.GetComponent <MaterialDensity> ().materialDensity;
float ricochetX = (angleX + impactAngleX);
if (ricochetX > 360)
{
ricochetX = (ricochetX - 360);
}
if (ricochetX < 0)
{
ricochetX = (ricochetX + 360);
}
float ricochetY = (angleY + impactAngleY);
if (ricochetY > 360)
{
ricochetY = (ricochetY - 360);
}
if (ricochetY < 0)
{
ricochetY = (ricochetY + 360);
}
float ricochetZ = (angleZ + impactAngleZ);
if (ricochetZ > 360)
{
ricochetZ = (ricochetZ - 360);
}
if (ricochetZ < 0)
{
ricochetZ = (ricochetZ + 360);
}
if ((ricochetX > 60 && ricochetX < 300) || (ricochetY > 60 && ricochetY < 300) || (ricochetZ > 60 && ricochetZ < 300)) {
ricochet = true;
//Debug.Log (ricochet);
}
if ((ricochetX < 60 && ricochetX > 300) || (ricochetY < 60 && ricochetY > 300) || (ricochetZ < 60 && ricochetZ > 300)) {
ricochet = false;
//Debug.Log (ricochet);
}
Debug.Log (ricochet);
Debug.Log (ricochetX);
Debug.Log (ricochetY);
Debug.Log (ricochetZ);
if (AP)
{
density *= 0.9f;
}
if (HP)
{
density *= 3f;
}
//float vel = gameObject.GetComponent<GunNew>().velocity;
float curVelocity = rb.velocity.magnitude;
float velocityMod = curVelocity / vel;
float densityMod = density / velocityMod;
float curEnergy = (kEnergy * velocityMod);
float energyMod = (curEnergy * velocityMod);
rb = GetComponent<Rigidbody> ();
//Quaternion localOffset = transform.rotation;
float randomX = Random.Range (0.03f, 0f);
float randomY = Random.Range (0.03f, -0.03f);
if (randomX == 0)
{
randomX = 0.01f;
}
if (randomY == 0)
{
randomY = 0.01f;
}
localOffset.x += randomX;
localOffset.y += randomY;
if (curVelocity > densityMod && !ricochet) {
rb.rotation = localOffset;
rb.velocity = transform.forward * ((curVelocity - (curVelocity * (randomX + randomY))) - densityMod);
//Debug.Log (curVelocity);
//Debug.Log (energyMod);
}
if (curVelocity > densityMod && ricochet)
{
Vector3 objAngle = new Vector3 (impactAngleX, impactAngleY, impactAngleZ);
Vector3 bulletAngle = rb.rotation.eulerAngles;
Debug.Log (objAngle);
}
if (curVelocity <= densityMod)
{
//Debug.Log (curVelocity);
//Debug.Log (energyMod);
Destroy (gameObject);
}
}
}
second code is a code from wall.
public float materialDensity = 100f;
public float angleX;
public float angleY;
public float angleZ;
//Quaternion localOffset = transform.rotation;
// Use this for initialization
public void Start ()
{
GetComponent<Rigidbody> ();
Quaternion localOffset = transform.rotation;
float angleX = localOffset.eulerAngles.x;
float angleY = localOffset.eulerAngles.y;
float angleZ = localOffset.eulerAngles.z;
//Debug.Log (localOffset.eulerAngles.x);
}
// Update is called once per frame
void Update () {
}
Firstly, I would make a layers in your game for things that will ricochet, and things that don't.
Then when you test for collisions with your bullet you can only check for collisions with the ricochet layer. This will increase performance and also make coding much simpler.
From there you could rely on unity's physics to do it's own ricochet, or if you wanted to calculate it yourself you could do a raycast and use the raycast's normal as described above.
if(Physics.Raycast (shootRay, out shootHit, range, ricochetMask)) {
...

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