Question by
trainoasis · Oct 06, 2020 at 10:13 AM ·
2drigidbody2dscalescaledown
Scale 2d rigidbody when moved farther "away" (y axis) based on Y position
I am not sure and have not found a solution to directly change Scale transform property of the 2d RigidBody when certain criteria are met. I want the rigidbody to simply be smaller when moved higher up so it seems as it is farther away. Any tips / links appreciated.
Edit; I figured that you have to move the GameObject and not the RigidBody of it.
This works:
player.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
But I would need to nicely change this scale based on y value of the object. The thing I do not understand is why the value only goes from, say -4.1 to about 0.7. What does this depend on?
For example, i have
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed; //Floating point variable to store the player's movement speed.
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
public GameObject player;
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
if(player == null) {
player = GameObject.FindWithTag("Player");
}
}
//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");
//Store the current vertical input in the float moveVertical.
float moveVertical = Input.GetAxis ("Vertical");
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.AddForce (movement * speed);
// player is moving
if(rb2d.velocity.magnitude > 0) {
Debug.Log("Player is moving.");
Debug.Log(rb2d.transform.position);
} else {
Debug.Log("Not moving.");
}
Debug.Log("Current Y position: " + rb2d.position.y);
// I WOULD ACTUALLY MOVE WITHOUT THIS CONDITION BASED ON rb2d.position.y .
// if the object is at the bottom of the arena then do not scale (keep 1, 1, 1), if it goes up scale
// down to, say, (0.2, 0.2, 0.2)
if(rb2d.position.y > -2.5) {
// scale
//Debug.Log("Scale it down");
Debug.Log(player.transform.localScale);
player.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
} else {
// reset scale to 1
//Debug.Log("Reset scale");
player.transform.localScale = new Vector3(1, 1, 1);
}
}
}
Where I scale the user
Comment