Gun is moving up and down with fps camera in unity - unity3d

I have downloaded my standard assests from unity 2017.1.4.But when i connect my gun with fps camera that gun is also moving up and down with the camera.

Im not sure i understand your problem but if you want to lock the object in place use:
Vector3 pos;
Quaternion rot;
private void Awake()
{
pos = gameObject.transform.position;
rot = gameObject.transform.rotation;
}
private void Update()
{
gameObject.transform.position = pos;
gameObject.transform.rotation = rot;
}
or even better this to set it from the editor:
[SerializeField] Vector3 pos;
[SerializeField] Quaternion rot;
private void Update()
{
gameObject.transform.position = pos;
gameObject.transform.rotation = rot;
}
If this wasn't it try to provide more information on your problem
Dont worry about the downvotes it happens even in the best families

Related

Why is my character falling/leaning over on mouse click in unity?

My character using CharacterController seems to be falling over! Is it the rotation that's the issue? I've been hitting my head against the wall for a few days trying to get this solved. any thoughts?
an small vid of what's happening: https://imgur.com/a/AyPvLtm
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class Player : MonoBehaviour
{
[SerializeField] private float playerSpeed = 10f;
[SerializeField] private float rotationSpeed = 8f;
public float SpeedChangeRate = 10.0f;
private Camera mainCamera;
private Vector3 targetPosition;
private CharacterController characterController;
private Coroutine coroutine;
private int groundLayer;
private void Awake() {
mainCamera = Camera.main;
characterController = GetComponent<CharacterController>();
groundLayer = LayerMask.NameToLayer("Ground");
}
void Update()
{
if (Mouse.current.leftButton.isPressed) Move();
}
private void Move() {
Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit);
if (hit.collider && hit.collider.gameObject.layer.CompareTo(groundLayer) == 0) {
if (coroutine != null) StopCoroutine(coroutine);
coroutine = StartCoroutine(PlayerMoveTowards(hit.point));
targetPosition = hit.point;
}
}
private IEnumerator PlayerMoveTowards(Vector3 target) {
while (Vector3.Distance(transform.position, target) > 0.1f) {
Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
Vector3 direction = target - transform.position;
Vector3 movement = direction.normalized * playerSpeed * Time.deltaTime;
characterController.Move(movement);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction.normalized), rotationSpeed * Time.deltaTime);
yield return null;
}
}
}
The reason is that at close distances, the difference between the main player's Target and Pivot point becomes very small and the height will be effective in determining the direction. Just set the direction Y to 0 to solve the problem.
Vector3 direction = target - transform.position;
direction.y = 0;
Figured this out.
It was my capsule collider. I had it set to the X-Axis, causing the collider to be rotated 90 degrees.
So my character would move and then flip to the side. Updating the collider direct to be on the Y-Axis fixed the problem.

Quaternion.lerp and position are being weird

So, I'm trying to have the camera follow the player (a car) and rotate with the player (... a car). However, it seems that either the quaternion.lerp is sus, or the positioning is. I've tried localPosition, but it doesn't really have an effect. It's rotating with the player, but it stays like... on one side of the player. Here is what I mean:
https://imgur.com/a/TQJOQ2X
and then
https://imgur.com/a/4FKm709
here's the code:
public class CameraMove : MonoBehaviour
{
[Header("References")]
[SerializeField] Transform player;
[Header("Attributes")]
[SerializeField] float camDelayIntensity = 1f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.localPosition = player.position + new Vector3(0, 3, -8);
Quaternion endPos = Quaternion.LookRotation(player.forward);
transform.rotation = Quaternion.Lerp(transform.rotation, endPos, camDelayIntensity);
}
}

cinemachine makes my camera movement laggy in unity

I'm curently using cinemachine to make a third person camera. My player's movements work and i wanted him to look in the direction he is moving but taking in consideration the rotation of the camera. It works when i don't move the camera while moving the player but when i move the camera the rotations of my player are laggy moreover every movement of my camera seems to be laggy too. Sorry for my english i hope it's clear here is my code :
public class ThirdPersonScript : MonoBehaviour
{
[SerializeField] private float speed;
[SerializeField] private float jumpForce;
[SerializeField] private Transform feet;
[SerializeField] private LayerMask floorMask;
[SerializeField] private Transform cam;
private Vector3 direction;
private Rigidbody rb;
private bool canJump;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;
if (direction.magnitude > 1.0f)
{
direction = direction.normalized;
}
direction *= speed;
canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
}
void FixedUpdate()
{
if (Physics.CheckSphere(feet.position, 0.1f, floorMask))
{
if (canJump)
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
else
rb.velocity = new Vector3(direction.x, 0, direction.z);
}
else
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
if (direction != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 1080*Time.fixedDeltaTime);
rb.MoveRotation(targetRotation);
}
}
}
and a screenshot of my cinemachine settings and my hierarchy :
Try change the direction in LateUpdate() but not Update() :
void LateUpdate()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;
if (direction.magnitude > 1.0f)
{
direction = direction.normalized;
}
direction *= speed;
canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
}
LateUpdate is called after all Update functions have been called. This is useful to order script execution. For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

Why is there a constant stutter when i move in Unity 2d?

So i have a simple scene in unity, a player with a parallax background and a Tilemap as a ground, as well as some very simple post processing. I know this isn't a The minute i move, there is a consistent stutter just under ever second. I'm not sure whether it's to do with my player movement code, camera movement or anything else. I'm also using a Cinemachine virtual camera. My rigidbody interpolation is set to interpolate and collision detection set to continuous. Here's my player movement if this helps. Here is a sample of what it looks like, if you look at the background or the tilemap it's quite noticeable. https://youtu.be/h2rSheZWtKs
[SerializeField] private LayerMask groundLayerMask;
public float speed;
public float Jump;
public sword swordScript;
public GameObject swordSprite;
private float move;
private Rigidbody2D rb;
private BoxCollider2D boxCollider2d;
private bool facingRight;
public SpriteRenderer spr;
public Animator PlayerAnims;
public bool movementAllowed;
void Awake()
{
Application.targetFrameRate = 60;
Application.targetFrameRate = Screen.currentResolution.refreshRate;
boxCollider2d = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
facingRight = true;
spr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
boxCollider2d = GetComponent<BoxCollider2D>();
rb = GetComponent<Rigidbody2D>();
facingRight = true;
spr = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void FixedUpdate()
{
if(movementAllowed == true)
{
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if (isGrounded() && Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector2(rb.velocity.x, Jump));
}
}
}
void Update()
{
move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(move * speed, rb.velocity.y);
if (movementAllowed == true)
{
Flip(move);
if (move == 0)
{
PlayerAnims.SetBool("isRunning", false);
}
else
{
PlayerAnims.SetBool("isRunning", true);
}
}
}
private bool isGrounded()
{
float extraHeightText = .1f;
RaycastHit2D raycasthit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, extraHeightText, groundLayerMask);
Color rayColour;
if (raycasthit2d.collider != null)
{
rayColour = Color.green;
PlayerAnims.SetBool("isJumping", false);
}
else
{
rayColour = Color.red;
PlayerAnims.SetBool("isJumping", true);
}
Debug.DrawRay(boxCollider2d.bounds.center + new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColour);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, 0), Vector2.down * (boxCollider2d.bounds.extents.y + extraHeightText), rayColour);
Debug.DrawRay(boxCollider2d.bounds.center - new Vector3(boxCollider2d.bounds.extents.x, boxCollider2d.bounds.extents.y + extraHeightText), Vector2.right * (boxCollider2d.bounds.extents.x), rayColour);
return raycasthit2d.collider != null;
}
private void Flip(float move)
{
if (move > 0 && !facingRight || move < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
if (swordScript.isFollowing == true)
{
Vector3 swordScale = swordSprite.transform.localScale;
swordScale.x *= -1;
swordSprite.transform.localScale = swordScale;
}
}
}
You are setting rb.velocity in both the Update() and FixedUpdate() methods. I would try only using one of those.
On top of that, your jump check also re-applies the X velocity along with the upward force. So if you're jumping the player will be pushed forward at double speed.
You also have an error being outputted in the console about an Index being out of range... I would look into that.
Can you also post your code for the parallax background?
FixedUpdate is a method where you want to do everything physics, player-controller and simulation related.
Update is just for rendering-related fluff i.e. code of no real consequence other than making things look correctly.
Hence:
Move all your player/physics controller code to FixedUpdate.
Move bg parallax code to Update.
Use Time.deltaTime (in Update) and Time.fixedDeltaTime (in FixedUpdate) time steps when animating or interpolating between values.
Ad #3.: Although - as #Menyus noted (below) - Time.deltaTime is all you really need.
Time.fixedDeltaTime is for that extra intent explicitness (but was necessary in earlier unity versions).

Rotate Camera vector to look at player Unity

I create a game, like minigolf/pool. I want to have a camera which follow player.
Position is normally ok, I get the ball direction and I lerp.
Rotation is almost ok. Currently, rotation by Y axis is ok, but camera look straigth forward, and don't look down to the player :
I already try many thing , quaternion angleToaxis, quarternion lookat ... but doesn't look good, the camera go look away ...
Here my code
namespace CameraManagerNameSpace
{
public class CameraManager : MonoBehaviour
{
public float cameraHeight=13f;
public PlayerNameSpace.Player playerToFollow;
public float followSpeed = 3f;
public float rotationSpeed = 1f;
float distance;
Vector3 position;
Vector3 newPos;
Quaternion rotation;
Quaternion newRot;
Vector3 playerPrevPos, playerMoveDir;
bool firstMoveDone=false;
void Start()
{
playerPrevPos = playerToFollow.player_transform.position;
distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
}
void FixedUpdate()
{
if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
{
playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
firstMoveDone = true;
}
else
{
playerMoveDir = new Vector3(0,0,0);
}
if (playerMoveDir != Vector3.zero)
{
playerMoveDir.Normalize();
newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);
position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);
transform.position = position;
transform.rotation = rotation;
playerPrevPos = playerToFollow.player_transform.position;
}
}
}
}
Also, I don't know why, but after the balls stop the camera continue to do some movement very jerky, jolting, halting.
Well in
newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);
you are saying the camera to look in the same direction the player is moving ... not to look at the player. This would work if you wouldn't give the camera an extra position offset in the Y axis.
You might want to rather try
// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);
You should also rather use Update since FixedUpdate is only used for physics related stuff (also see Update & FixedUpdate)