I can't configure how high the character jumps. (unity 2d) - unity3d

I've got a script from a tutorial that makes my player jump when you press a button but I don't know how to configure how high it jumps. Heres the code:
var before : Sprite;
var after : Sprite;
var isGrounded : boolean;
var Animator : Animator;
var character : GameObject;
var jump : float = 0;
var jumpSpeed : float = 5;
var jumpTimer : float = 0;
function Start () {
isGrounded = true;
}
function Update () {
Animator.SetBool("isGrounded", isGrounded);
if(jump == 1) {
jumpTimer = jumpTimer + 1;
}
if(jumpTimer >= 50) {
jumpTimer = 0;
jump = 0;
}
}
function OnMouseDown () {
isGrounded = false;
GetComponent(SpriteRenderer).sprite = after;
if(jump == 0) {
character.GetComponent(Rigidbody2D).velocity.y = jumpSpeed;
jump = 1;
}
yield WaitForSeconds (0.5);
isGrounded = true;
}
function OnMouseUp () {
GetComponent(SpriteRenderer).sprite = before;
}
I tried lowering the floats for jump/jumpspeed/jumptimer but it just won't work. Any ideas?

Placing my comment into an answer for anyone else using the same tutorial and having the same issue.
The line below is used to alter the players y velocity.
character.GetComponent(Rigidbody2D).velocity.y = jumpSpeed;
In order to change the jump height of the player, you will need to alter the jumpSpeed variable.
Note
If you are altering the jumpSpeed variable at the top of the script and it isn't changing, it is because the value in the inspector overrides the value entered at the top of the script.

Related

Unity 2D Camera Zooms in when character moves, but properties of the camera do not change

After I click play the camera stays as it should be, but when I move my character the camera zooms in for no reason
The properties of the camera do not change at all, zoom and everything stays the same. Tryed changing from orthographic to perspective no change, move z axis no change, change scale no change, change resolution and no change, making the camera not a parent and no change it behaves the same as parent and as child
before character walks
after character walks
I dont think that there is something to do with the code but here is the code attached to my character, the camera behaves the same as child and as parent
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public float speed = 5f;
public float jumpSpeed = 8f;
private float movementX = 0f;
private Rigidbody2D rigidBody;
public Transform groundCheckPoint;
public float groundCheckRadius;
public LayerMask groundLayer;
public bool isTouchingGround;
public SpriteRenderer box;
private bool canSpawn = true;
private bool canAnimateWalk = true;
private bool canAnimateIdle = true;
private bool canAnimateJump = true;
private bool stopJump = true;
private int spawningSpeed = 1000;
// Use this for initialization
void Start()
{
rigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
isTouchingGround = Physics2D.OverlapBox(groundCheckPoint.position,new Vector2(0.9f,0.1f),0f, groundLayer);
movementX = Input.GetAxis("Horizontal");
if (movementX > 0f)
{
if(canAnimateWalk==true && isTouchingGround)
{
canAnimateWalk = false;
StartCoroutine(AnimateWalk());
}
GetComponent<SpriteRenderer>().transform.localScale = new Vector3(2, 2, 1);
rigidBody.velocity = new Vector2(movementX * speed, rigidBody.velocity.y);
}
else if (movementX < 0f)
{
if (canAnimateWalk == true && isTouchingGround)
{
canAnimateWalk = false;
StartCoroutine(AnimateWalk());
}
GetComponent<SpriteRenderer>().transform.localScale = new Vector3(-2, 2, 1);
rigidBody.velocity = new Vector2(movementX * speed, rigidBody.velocity.y);
}
else
{
if(isTouchingGround)
{
StopCoroutine(AnimateWalk());
if(canAnimateIdle==true)
{
canAnimateIdle = false;
StartCoroutine(AnimateIdle());
}
}
rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
}
if (Input.GetButtonDown("Jump") && isTouchingGround)
{
canAnimateJump = false;
rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
StartCoroutine(AnimateJump());
}
else if(!isTouchingGround)
{
StopCoroutine(AnimateWalk());
}
}
IEnumerator AnimateJump()
{
Debug.Log("Animating Jump");
int counter = 0;
while (counter < 10)
{
counter++;
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("img/j" + counter);
yield return new WaitForSeconds(0.1f);
if(isTouchingGround==true)
{
break;
}
}
while(!isTouchingGround)
{
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("img/j10");
yield return new WaitForSeconds(0.1f);
}
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("img/i1");
canAnimateWalk = true;
canAnimateJump = true;
}
IEnumerator AnimateIdle()
{
int counter = 0;
while(Input.GetAxis("Horizontal")==0 && counter <10 && rigidBody.velocity.y==0)
{
counter++;
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("img/i"+counter);
yield return new WaitForSeconds(0.2f);
}
canAnimateIdle = true;
}
IEnumerator AnimateWalk()
{
int counter = 0;
while (Input.GetAxis("Horizontal")!=0 && counter < 8 && rigidBody.velocity.y==0)
{
counter++;
GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("img/g" + counter);
yield return new WaitForSeconds(0.08f);
}
canAnimateWalk = true;
}
}
What could it be? I tried everything I think
GetComponent<SpriteRenderer>().transform.localScale = new Vector3(-2, 2, 1);
If your movement script is attached to your "guy" gameobject, then you are changing the (local) scale of it. All children will also scale accordingly.
Since your camera is a child of guy, it will scale and produce the result you see.
Try unparenting the Camera from your guy and create a seperate script that follows your guy and attach that to your Camera.
I solved my problem
The issue was in the character scaling. The camera did not change but the size of the character did making me believe that there was a zoom in.
My character x and y scale is 1 and 1 but I used 2 and 2 scale on move
The scale was used to rotate my character when it moves left and right

Parent object not accessing variables from children's script

I'm working on a project in Unity and I've created a script called DeerHater that targets the transform and controller of an object that enters the specified area. The script by itself works but it's connected to a parent object that has it's controller attached and that controller is supposed to access the variables of DeerHater and then do specified functions.
The problem is that the variables in controller doesn't change from empty to the variables that has changed in DeerHater since the desired object entered the trigger and it showups these two errors:
NullReferenceException: Object reference not set to an instance of an object
MissingFieldException: DeerController.targetDeer
I can't really see where the problem is since I'm a total beginner, could anyone tell me why wouldn't it acces DeerHater variables?
BearController script (parent object):
var distanceDeer : float;
var deerHater : DeerHater;
var deer : GameObject = null;
var targetDeer : Transform;
var isFollowing : boolean = false;
var center : Transform;
var deerKilled : boolean = false;
function Start()
{
deerHater = GameObject.Find("DeerHater").GetComponent(DeerHater);
}
function Update()
{
deer = deerHater.deerController.
targetDeer = deerHater.stupidDeer;
distanceDeer = Vector3.Distance(deerHater.stupidDeer.position, transform.position);
if(deerHater.collisionDeer == true)
{
ChaseDeer();
if(distanceDeer < attackRange)
{
deer.health = -0.1;
deerKilled = true;
}
if(deerKilled == true)
{
GoBack();
deerKilled = false;
}
}
}
function ChaseDeer()
{
var rotation = Quaternion.LookRotation(deerHater.stupidDeer.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
moveSpeed = 6;
animation.Play("Run");
animation["Run"].speed = 1.25;
moveDirection = transform.forward;
moveDirection *= moveSpeed;
isFollowing = true;
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
And here's the DeerHater script:
#pragma strict
var stupidDeer : Transform;
var deerController : DeerController;
public var collisionDeer : boolean = false;
function OnTriggerEnter(col : Collider)
{
if(col.gameObject.tag == "Deer")
{
collisionDeer = true;
stupidDeer = col.gameObject.transform;
deerController = col.gameObject.GetComponent(DeerController);
}
}
function OnTriggerExit(col : Collider)
{
if(col.gameObject.tag == "Deer")
{
collisionDeer = false;
stupidDeer = null;
deerController = null;
}
}
Thanks in advance!
I've managed to fix this by placing DeerHater code inside the BeerController and moving the deer variables from global variables to if(deerCollision == true).

Google Cardboard Magnet Refresh Not Working in Unity3d

I am working on a Unity project using google cardboard, basing my design on Cardboard Catapult, cardboard magnet to make a ball jump and it works the first time, but whenever the game restarts, using Application.LoadLevel(), the ball doesn’t jump anymore; it just glitches. I used this script. I have tested this script (Magnet Sensor Script) with a test application where whenever the magnet is pulled, the text will change color and it works all the time. Here’s my Ball Control Script (the script I called the Magnet Sensing):
#pragma strict
var rotationSpeed = 100;
var jumpHeight = 8;
var Hit01 : AudioClip;
var Hit02 : AudioClip;
var Hit03 : AudioClip;
var distToGround : float;
function Start () {
// Getting the distance from the center to the ground.
distToGround = collider.bounds.extents.y;
}
function Update ()
{
//Handle ball rotation.
var rotation : float = Input.GetAxis(“Horizontal”) * rotationSpeed;
rotation *= Time.deltaTime;
rigidbody.AddRelativeTorque (Vector3.back * rotation);
MagnetSensor.OnMagnetPull += JumpOnMagnet; //important
}
function JumpOnMagnet () { //important
rigidbody.velocity.y = jumpHeight; //important
} //important
function IsGrounded () : boolean { //Check if we are on the ground. Return true if we are else return null.
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}
function OnCollisionEnter () {
var theHit = Random.Range(0, 3);
if (theHit == 0)
{
audio.clip = Hit01;
}
else if (theHit == 1)
{
audio.clip = Hit02;
}
else {
audio.clip = Hit03;
}
audio.pitch = Random.Range (0.9,1.1);
audio.Play();
}
Here’s my script for the restart:
#pragma strict
var maxFallDistance = -10;
private var isRestarting = false;
var level : String;
var GameOverSound : AudioClip;
function Update ()
{
if (transform.position.y <= maxFallDistance)
{
if (isRestarting == false)
{
RestartLevel();
}
}
}
function RestartLevel () {
isRestarting = true;
audio.pitch = 1;
audio.clip = GameOverSound;
audio.Play();
yield WaitForSeconds (audio.clip.length);
Application.LoadLevel(level);
}
Please let me know what the possible issues could be and how I can fix them. Also, I’d appreciate if you can point me to any website or resource that can help.
Don't do MagnetSensor.OnMagnetPull += JumpOnMagnet; in the Update() function. Call it in Start(), so it is only added once.
Also, you should add an OnDestroy() function and call MagnetSensor.OnMagnetPull -= JumpOnMagnet; in it.

Unity game engine having camera follow script transform change depending on car selected script?

OVERALL GOAL: Have the camera change target to the selected car
I'm new to the unity game engine and got a bit of a problem.
So, I have a successful car selector which changes between cars and starts the match with that car. Everything there works. The only issue is that my "CarCameraScript" has a transform variable which is always 1 of the 3 cars. I want it to change dependant on the selected car.
Here is the look at the code of the CarCameraScript
#pragma strict
var car : Transform;
var distance: float = 6.4;
var height: float = 1.4;
var rotationDamping : float = 3.0;
var heightDamping: float = 2.0;
var zoomRatio : float = 0.5;
var DefaultFOV : float = 60;
private var rotationVector : Vector3;
function Start () {
}
function LateUpdate () {
var wantedAngel = rotationVector.y;
var wantedHeight = car.position.y + height;
var myAngel = transform.eulerAngles.y;
var myHeight = transform.position.y;
myAngel = Mathf.LerpAngle(myAngel,wantedAngel,rotationDamping*Time.deltaTime);
myHeight = Mathf.Lerp(myHeight,wantedHeight,heightDamping*Time.deltaTime);
var currentRotation = Quaternion.Euler(0,myAngel,0);
transform.position = car.position;
transform.position -= currentRotation*Vector3.forward*distance;
transform.position.y = myHeight;
transform.LookAt(car);
}
function FixedUpdate () {
var localVilocity = car.InverseTransformDirection(car.rigidbody.velocity);
if (localVilocity.z<-0.5) {
rotationVector.y = car.eulerAngles.y + 180;
} else {
rotationVector.y = car.eulerAngles.y;
}
var acc = car.rigidbody.velocity.magnitude;
camera.fieldOfView = DefaultFOV + acc*zoomRatio;
}
This is what it looks like on the side panel.
http://i.stack.imgur.com/lYJP7.jpg
The area that says none (transform) is the place that should be variable dependant on the currently selected car.
Now, Here is my other script being the CharacterSelectScript
#pragma strict
//this is the currently selected Player. Also the one that will be saved to PlayerPrefs
var selectedPlayer : int = 0;
function Update()
{
if (Input.GetMouseButtonUp (0)) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
// The pink text is where you would put the name of the object you want to click on (has attached collider).
if(hit.collider.name == "Player1")
SelectedCharacter1(); //Sends this click down to a function called "SelectedCharacter1(). Which is where all of our stuff happens.
if(hit.collider.name == "Player2")
SelectedCharacter2();
if(hit.collider.name == "Player3")
SelectedCharacter3();
}
else
{
return;
}
}
}
function SelectedCharacter1() {
Debug.Log ("Character 1 SELECTED"); //Print out in the Unity console which character was selected.
selectedPlayer = 1;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter2() {
Debug.Log ("Character 2 SELECTED");
selectedPlayer = 2;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
function SelectedCharacter3() {
Debug.Log ("Character 3 SELECTED");
selectedPlayer = 3;
PlayerPrefs.SetInt("selectedPlayer", (selectedPlayer));
}
How would I get it so that the SelectedPlayer changes the transform in the first script?
Any ideas?
I also have the prefab script which probably isnt important.
Also, should I join both scripts into one?
OVERALL GOAL: Have the camera change target to the selected car

Tracking distance. Unity 2D game

If I have a object that starts at 0 on the x axis, and moving it in the x+ axis. Is there a way I can track that distance made, and use it counter?
I have no clue what im doing, but was thinking something like
var distance = orgpos -> currentpos;
for each x10{
score += 1; }
And this action performed live while moving.
Edit:
calculatedDistance += (transform.position - previousPosition).magnitude;
previousPosition = transform.position;
I have this script that give me the distance, if thats to any help.
Found a way after I posted the question. Ill just post the way I did it for others to use.
//Score
static var score : int = 0;
static var distanceScore : int = 0;
static var starScore : int = 0;
//Adding point and removing star for each collision
function OnCollisionEnter(collision : Collision)
{
if (collision.gameObject.tag == "StarPickup")
{
Destroy(collision.gameObject);
starScore += 10;
}}
// Checking distance
var previousPosition : Vector3;
var calculatedDistance : float;
function Awake()
{
previousPosition = transform.position;
}
function Update()
{
calculatedDistance += (transform.position - previousPosition).magnitude;
previousPosition = transform.position;
distanceScore = Mathf.Round(calculatedDistance/10);
score = distanceScore + starScore;
print("The score is: " + score);
}