localScale is not working at the runtime after applying the Animator component - unity3d

I apply an animator component to my Game Object. After that when I play the game, I try to change the localScale of the game object but it doesn't work.
Here is my code to change the game object's localScale according to its direction on the x coordinate.
private Rigidbody2D rb;
private Vector3 direction;
private Animator anim;
private bool isLookingRight;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
isLookingRight = false;
}
private void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
TurnDirection(horizontal);
}
// turns the player towards to movement direction
private void TurnDirection(float horizontal)
{
if (horizontal > 0 && !isLookingRight || horizontal < 0 && isLookingRight)
{
isLookingRight = !isLookingRight;
direction = transform.localScale;
direction.x *= -1;
transform.localScale = direction;
}
}
It worked well before applying the animation to the Game Object. I can't change the scale of the Game Object even manually on the inspector while playing the game.

This is probably caused by keyframes controlling localScale in the animation file. If you don't need it, you can solve the problem by deleting these keyframes from the animation window.
See here

Related

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

Unity 2D Top-Down mouse facing weapon rotation problem

I am making a Top-Down 2D shooting game and i did spot a trouble.
The point is, player gun has weird rotation whenever the player rotate.
I made my Player face mouse position. Player gun is not in the center of sprite.
The Gun is a prefab in PlayerHand and PlayerHand is a Child of Player.
I tried a lot of things and yet still i cant find a solution.
public class HandHolder : MonoBehaviour
{
[SerializeField] Gun gun;
[SerializeField] float offsetX;
[SerializeField] float offsetY = 0.01f;
Gun playerGun;
void Awake ()
{
playerGun = Instantiate(gun,transform.localPosition,transform.localRotation) as Gun;
}
// Update is called once per frame
void Update ()
{
playerGun.transform.position = new Vector3(transform.position.x + offsetX,transform.position.y + offsetY);
playerGun.transform.rotation = transform.rotation;
playerGun.Shooting();
}
}
void Update()
{
if (!isLocalPlayer)
return;
Vector3 position = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * Time.deltaTime * 20f;
transform.position += position;
FaceMouse();
}
public void FaceMouse()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
mousePosition.Normalize();
float rotation_z = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotation_z);
}
Here are the screenshoots. My Player already has a gun in texture. but it is only texture. I want the Gun prefab to be exactly on the place of Player sprite gun, whenever i rotate.
add an empty to your player, name it gunTransform. tag it GunTransform make sure the forward axis(blue) is facing the players forward direction.
Class Level variable -
Transform guntransform;
in Awake():
guntransform=this.GameObject.FindObjectWithTag("GunTransform").getComponent<Transform>();
then instead of
playerGun = Instantiate(gun, transform.localPosition, transform.localRotation) as Gun;
call
playerGun = Instantiate(gun, guntransform.position, guntransform.rotation) as Gun;

unity3d: Camera does not follow the player

I am fairly new in game development, I have a piece of code that makes camera move based on player's movement.
player's movement script:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
//to store movement
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLenghth = 100f;
//gets called regardless if the script is enabled or not
void Awake(){
floorMask = LayerMask.GetMask ("Floor");
playerRigidbody = GetComponent<Rigidbody> ();
//Input.ResetInputAxes ();
}
//unity calls automatically on every script and fire any physics object
void FixedUpdate(){
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
//Rotate ();
Turning ();
}
void Move(float h, float v){
movement.Set (h,0f,v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning (){
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (camRay,out floorHit,camRayLenghth,floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
}
and here is the script attached to the main camera:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
// a target for camera to follow
public Transform player;
// how fast the camera moves
public float smoothing = 4f;
//the initial offset from the target
Vector3 offset;
void start(){
//calculation of initial offset (distance) between player and camera
offset = transform.position - player.position;
Debug.Log ("offset is " + offset);
}
void FixedUpdate (){
//updates the position of the camera based on the player's position and offset
Vector3 playerCameraPosition = player.position + offset;
//make an smooth transfer of location of camera using lerp
transform.position = Vector3.Lerp(transform.position, playerCameraPosition, smoothing * Time.deltaTime);
}
}
but when I attach the script to my main camera, as soon as I play test the game camera starts to relocate and moves towards the ground even though the player hasn't moved yet. If I remove the script from the camera and make the camera the child of the player, as soon as I hit play, camera starts to rotate around the object.
Please give me some hints what am I doing wrong ?
The camera offset isn't being set because of the lower case on your start method. This means the offset remains at its default value which is 0,0,0 causing your camera to move to some funky place.
Change: `
void start() {
...
}
to
void Start() {
...
}
see you don't need any code for this just make you camera a child of your player object..
drag you camera object onto the player object in hierarchy

Stop Player/User from multi jump in my Unity game

Hello and thanks for reading this post.
I'm new to Unity but regardless of this I managed to make a small 2d game. But I ran into a little problem with the jump function.
The player / user shouldn't be able to multi jump in the game.
This is the C# script that controls the player.
using UnityEngine;
using System.Collections;
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
public GameObject player;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
//to check ground and to have a jumpforce we can change in the editor
bool grounded = true;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700f;
// Use this for initialization
void Start () {
//set anim to our animator
anim = GetComponent <Animator>();
}
void FixedUpdate () {
//set our vSpeed
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
//set our grounded bool
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
//set ground in our Animator to match grounded
anim.SetBool ("Ground", grounded);
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move > 0 && !facingLeft) {
Flip ();
} else if (move < 0 && facingLeft) {
Flip ();
}
}
void Update(){
//if we are on the ground and the space bar was pressed, change our ground state and add an upward force
if(grounded && Input.GetKeyDown (KeyCode.UpArrow)){
anim.SetBool("Ground",false);
rigidbody2D.AddForce (new Vector2(0,jumpForce));
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
And here is the Player object and the GroundCheck Object.
How can I stop the player from being able to multijump. So if he press the upArrow key, He will jump and not be able to jump again before he lands.
Thanks for your time and help
Update
If its hard to see the Images here are the Image on Imgur:
http://imgur.com/GKf4bgi,2i7A0AU#0
You can add another Collider to your player GameObject and make it a trigger with Is Trigger option. Use this code to change a flag variable telling if player is on ground:
private bool isOnGround = false;
void OnCollisionEnter2D(Collision2D collision) {
isOnGround = true;
}
void OnCollisionExit2D(Collision2D collision) {
isOnGround = false;
}
Then you can allow jumping only when isOnGround is true.
You could make little game object called groundController, place it under player.
You're setting there bool value for grounded and in code your checking if your controller overlaps with ground.
watch it here for more info: http://youtu.be/Xnyb2f6Qqzg?t=45m22s