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

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

Related

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.

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

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.

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);
}

Unity3D Third Person Controller and Animations

My problem is that a custom walk animation I have set in the third person controller of Unity3D is not shown.
The animation is imported from a FBX file with the model#walk.fbx structure. I know the animation works, because if I use it as the idle animation it shows. On the other hand, it also doesn't seem to be an issue with the controller script, as it works fine with the prototype character.
It seems that the animation being played is the one selected in the Animation component (which has 'Play Automatically' selected). Any attempts to change the animation from the third person controller work for the prototype character, but not for mine.
I don't have nor want run and jump animations. With the prototype character I set the walk animation on each of those with no adverse effects. The controller doesn't turn off animation this way, seeing that there are no log entries in the console from the third person controller script. The relevant line with the CrossFade call is getting called.
Any clues as to where I could look next? Is it more likely an issue with the controller, or with the animation? Something else completely?
Update: Below is the code of my controller. It works fine when I use the sample model of the construction worker that is provided with Unity. The lines with _animation.CrossFade are getting called at the expected times. Using Play or Blend instead doesn't help. There are no errors logged in the console.
For our custom animations however it doesn't work. I am now suspecting the issues lies with the model. Unfortunately I am not at liberty to share a sample of that model. I've asked the animator for further details on how he created the FBX export. Are there any specific settings he needs to use for the model to work in Unity? It remains odd though that the animations do work if I add them indepently to the scene.
// Require a character controller to be attached to the same game object
#script RequireComponent(CharacterController)
public var idleAnimation : AnimationClip;
public var walkAnimation : AnimationClip;
public var walkMaxAnimationSpeed : float = 0.75;
private var _animation : Animation;
enum CharacterState {
Idle = 0,
Walking = 1,
}
private var _characterState : CharacterState;
// The speed when walking
var walkSpeed = 2.0;
var speedSmoothing = 10.0;
var rotateSpeed = 500.0;
var targetPrecision = 5;
var targetMaxDistance = 200;
// The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
private var lockCameraTimer = 0.0;
// The current move direction in x-z
private var moveDirection = Vector3.zero;
// The current x-z move speed
private var moveSpeed = 0.0;
// The last collision flags returned from controller.Move
private var collisionFlags : CollisionFlags;
// Are we moving backwards (This locks the camera to not do a 180 degree spin)
private var movingBack = false;
// Is the user pressing any keys?
private var isMoving = false;
private var isControllable = true;
private var isTargetting : boolean = false;
private var targetPoint : Vector3 = Vector3.zero;
function Awake () {
moveDirection = transform.TransformDirection(Vector3.forward);
_animation = GetComponent(Animation);
if(!_animation)
Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
if(!idleAnimation) {
_animation = null;
Debug.Log("No idle animation found. Turning off animations.");
}
//_animation[idleAnimation.name] = idleAnimation;
if(!walkAnimation) {
_animation = null;
Debug.Log("No walk animation found. Turning off animations.");
}
//_animation[walkAnimation.name] = walkAnimation;
}
function UpdateSmoothedMovementDirection () {
var cameraTransform = Camera.main.transform;
// Forward vector relative to the camera along the x-z plane
var forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
// Right vector relative to the camera
// Always orthogonal to the forward vector
var right = Vector3(forward.z, 0, -forward.x);
var v = Input.GetAxisRaw("Vertical");
var h = Input.GetAxisRaw("Horizontal");
// Are we moving backwards or looking backwards
if (v < -0.2)
movingBack = true;
else
movingBack = false;
var wasMoving = isMoving;
isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;
// Target direction relative to the camera
var targetDirection = h * right + v * forward;
// Lock camera for short period when transitioning moving & standing still
lockCameraTimer += Time.deltaTime;
if (isMoving != wasMoving)
lockCameraTimer = 0.0;
// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero) {
// If we are really slow, just snap to the target direction
if (moveSpeed < walkSpeed * 0.9) {
moveDirection = targetDirection.normalized;
}
// Otherwise smoothly turn towards it
else {
moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
moveDirection = moveDirection.normalized;
}
}
// Smooth the speed based on the current target direction
var curSmooth = speedSmoothing * Time.deltaTime;
// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);
_characterState = CharacterState.Idle;
// Pick speed modifier
targetSpeed *= walkSpeed;
_characterState = CharacterState.Walking;
moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
}
function UpdateTargettedMovementDirection () {
var cameraTransform = Camera.main.transform;
var wasMoving = isMoving;
isMoving = true;//Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;
// Target direction relative to the camera
// var targetDirection = h * right + v * forward;
var targetDirection = Vector3.zero;
targetDirection.x = targetPoint.x - transform.position.x;
targetDirection.z = targetPoint.z - transform.position.z;
targetDirection = targetDirection.normalized;
//Debug.Log("Target direction is " + targetDirection);
// Lock camera for short period when transitioning moving & standing still
lockCameraTimer += Time.deltaTime;
if (isMoving != wasMoving)
lockCameraTimer = 0.0;
// We store speed and direction seperately,
// so that when the character stands still we still have a valid forward direction
// moveDirection is always normalized, and we only update it if there is user input.
if (targetDirection != Vector3.zero) {
// If we are really slow, just snap to the target direction
if (moveSpeed < walkSpeed * 0.9) {
moveDirection = targetDirection.normalized;
}
// Otherwise smoothly turn towards it
else {
moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
moveDirection = moveDirection.normalized;
}
}
// Smooth the speed based on the current target direction
var curSmooth = speedSmoothing * Time.deltaTime;
// Choose target speed
//* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);
_characterState = CharacterState.Idle;
// Pick speed modifier
targetSpeed *= walkSpeed;
_characterState = CharacterState.Walking;
moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
}
function Update() {
if (!isControllable) {
// kill all inputs if not controllable.
Input.ResetInputAxes();
}
var distance : float = 0;
if (Input.GetMouseButtonUp(0)) {
if (isTargetting) {
isTargetting = false;
// Debug.Log("Stopped moving");
FaceCamera();
} else {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var layerMask = 1 << 8; // Terrain is layer 8
var hit : RaycastHit;
Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000, layerMask);
distance = Vector3.Distance(transform.position, hit.point);
if (distance <= targetMaxDistance && hit.point != Vector3.zero) {
targetPoint = hit.point;
isTargetting = true;
// Debug.Log("Mouse up at hit " + hit.point + " at distance " + distance);
} else {
isTargetting = false;
// Debug.Log("Ignored mouse up at hit " + hit.point + " at distance " + distance);
}
}
}
if (isTargetting) {
// Debug.Log("Moving to " + targetPoint);
distance = Vector3.Distance(transform.position, targetPoint);
if (distance < targetPrecision) {
// Debug.Log("Reached point " + targetPoint + " at distance " + distance);
isTargetting = false;
FaceCamera();
} else {
UpdateTargettedMovementDirection();
}
} else {
UpdateSmoothedMovementDirection();
}
// Calculate actual motion
var movement = moveDirection * moveSpeed;
movement *= Time.deltaTime;
// Move the controller
var controller : CharacterController = GetComponent(CharacterController);
collisionFlags = controller.Move(movement);
// ANIMATION sector
if (_animation) {
if (controller.velocity.sqrMagnitude < 0.1) {
_animation.CrossFade(idleAnimation.name);
} else {
//_animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);
_animation.CrossFade(walkAnimation.name);
}
} else {
Debug.Log("Animation is null!");
}
// ANIMATION sector
// Set rotation to the move direction
transform.rotation = Quaternion.LookRotation(moveDirection);
}
function OnControllerColliderHit (hit : ControllerColliderHit ) {
// Debug.DrawRay(hit.point, hit.normal);
if (hit.moveDirection.y > 0.01)
return;
}
function GetSpeed () {
return moveSpeed;
}
function GetDirection () {
return moveDirection;
}
function IsMovingBackwards () {
return movingBack;
}
function GetLockCameraTimer () {
return lockCameraTimer;
}
function IsMoving () : boolean {
return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
}
function Reset () {
gameObject.tag = "Player";
}
function FaceCamera() {
var cameraTransform = Camera.main.transform;
// Forward vector relative to the camera along the x-z plane
var forward = cameraTransform.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
moveDirection = -forward;
}
Update 2: The settings used to create the animations are in these screenshots. Are they correct?
Not (yet :-) an answer but I need more space and images.
Since 3.5 Unity3d the way to handle imports based on animation#model.fbx notation has changed and some people reported trouble (s. for example BIG Unity 3.5.0f1 problem with Skinned Rig - Major FAIL). The problem arises when a 2nd root bone comes to play but I could solve this by dragging the animations to the model file prefab (most of my animations are contained in the model and the remaining 2 are no big pain).
Just to be really sure that I understood your answer in the comments section right, you have something like this:
That means:
Within the character model the animations array contains all animations
The number of bones and all names are exactly like in your prototype character
If you open an animation view, you can see a read-only list of all animations of the character selected in hierarchy view
Assuming this is fine some more suggestions:
I can't see any place in the code where you set WrapMode.Loop or animation speed. Are you sure it is configured as Loop in inspector and is not overwritten somewhere.
CrossFade with no parameters assumes 0.3 seconds
What happens after the cross fade call? Does the DefaulTake stops playing?
Can you drag the Walk animation as default
Do you use different animation layers?
What output do you get when you set up Debug.Log ("Walk: " + player.animation.IsPlaying ("Walk"));
[Update]
Let's look at the import settings. Do you have Split Animations
checked and are there maybe wrong values entered at Start and
End like 1-1?
Regarding Toggling of IsPlaying: Please create more output about the AnimationState properties. Most notable speed, length, enabled, weight, ... I have a suspicion that the animation is too short or played too fast.
A walk animation that is no bone animation sounds a bit strange. On the other hand console would cry out loud if bone names are not matching. So I assume there is no problem now.
That is strange, can you post the source&demo?
You can try to check:
Check if the animation names and properties are set correctly in the editor.
Create an object without the controller and make sure the animations were imported correctly.