Unity setting localEulerAngles causes unexpected result - unity3d

I have the following code:
if (Input.GetKeyDown(KeyCode.A))
{
var rot = switchTransform.localEulerAngles;
Debug.Log(rot);
rot.x = 150;
switchTransform.localEulerAngles = rot;
}
When I click 'A', the switchTransform switches from (30, 0, 0) to (150, 0, 0) in the inspector and (30, 0, 0) to (30, 180, 180) in the console.
It works correctly if I write it like this:
angle = 150f;
if (Mathf.Abs(angle) <= 180 && Mathf.Abs(angle) > float.Epsilon)
{
angle = 180 - angle;
}
if (Input.GetKeyDown(KeyCode.A))
{
var rot = switchTransform.localEulerAngles;
rot.x = angle;
switchTransform.localEulerAngles = rot;
}
Why does it happen, and is there a better way to work around it?
This is the switch transform, as you can see it has unusual pivot.

Related

How to control the jump of my RigidbodyFPSController?

I want to control the jump of my RigidBodyFPSController ( a Unity5 script) for a survival game.
The problem is that:
I don't know where is the isJumping variable (forExample, type bool) which allow my character can jump. I want to manipulate that variable to change it to false when my character have low stamina.
What is the way to do that?
var size : Vector2 = new Vector2(240, 40);
//Health Variables
var healthPos : Vector2 = new Vector2(20, 20);
var healthBarDisplay : float = 1;
var healthBarEmpty : Texture2D;
var healthBarFull : Texture2D;
//Hunger Variables
var hungerPos : Vector2 = new Vector2(20, 60);
var hungerBarDisplay : float = 1;
var hungerBarEmpty : Texture2D;
var hungerBarFull : Texture2D;
//Thirst Variables
var thirstPos : Vector2 = new Vector2(20, 100);
var thirstBarDisplay : float = 1;
var thirstBarEmpty : Texture2D;
var thirstBarFull : Texture2D;
//Stamina Variables
var staminaPos : Vector2 = new Vector2(20, 140);
var staminaBarDisplay : float = 1;
var staminaBarEmpty : Texture2D;
var staminaBarFull : Texture2D;
//Fall Rate
var healthFallRate : int = 150;
var hungerFallRate : int = 150;
var thirstFallRate : int = 100;
var staminaFallRate : int = 35;
private var chMotor : CharacterMotor;
private var controller : CharacterController;
var canJump : boolean = false;
var jumpTimer : float = 0.7;
function Start()
{
chMotor = GetComponent(CharacterMotor);
controller = GetComponent(CharacterController);
}
function OnGUI()
{
//Health GUI
GUI.BeginGroup(new Rect (healthPos.x, healthPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * healthBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), healthBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Hunger GUI
GUI.BeginGroup(new Rect (hungerPos.x, hungerPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * hungerBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), hungerBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Thirst GUI
GUI.BeginGroup(new Rect (thirstPos.x, thirstPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * thirstBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), thirstBarFull);
GUI.EndGroup();
GUI.EndGroup();
//Stamina GUI
GUI.BeginGroup(new Rect (staminaPos.x, staminaPos.y, size.x, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarEmpty);
GUI.BeginGroup(new Rect (0, 0, size.x * staminaBarDisplay, size.y));
GUI.Box(Rect(0, 0, size.x, size.y), staminaBarFull);
GUI.EndGroup();
GUI.EndGroup();
}
function Update()
{
//HEALTH CONTROL SECTION
if(hungerBarDisplay <= 0 && (thirstBarDisplay <= 0))
{
healthBarDisplay -= Time.deltaTime / healthFallRate * 2;
}
else
{
if(hungerBarDisplay <= 0 || thirstBarDisplay <= 0)
{
healthBarDisplay -= Time.deltaTime / healthFallRate;
}
}
if(healthBarDisplay <= 0)
{
CharacterDeath();
}
//HUNGER CONTROL SECTION
if(hungerBarDisplay >= 0)
{
hungerBarDisplay -= Time.deltaTime / hungerFallRate;
}
if(hungerBarDisplay <= 0)
{
hungerBarDisplay = 0;
}
if(hungerBarDisplay >= 1)
{
hungerBarDisplay = 1;
}
//THIRST CONTROL SECTION
if(thirstBarDisplay >= 0)
{
thirstBarDisplay -= Time.deltaTime / thirstFallRate;
}
if(thirstBarDisplay <= 0)
{
thirstBarDisplay = 0;
}
if(thirstBarDisplay >= 1)
{
thirstBarDisplay = 1;
}
//STAMINA CONTROL SECTION
if(controller.velocity.magnitude > 0 && Input.GetKey(KeyCode.LeftShift))
{
chMotor.movement.maxForwardSpeed = 10;
chMotor.movement.maxSidewaysSpeed = 10;
staminaBarDisplay -= Time.deltaTime / staminaFallRate;
}
else
{
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
staminaBarDisplay += Time.deltaTime / staminaFallRate;
}
//JUMPING SECTION
if(Input.GetKeyDown(KeyCode.Space) && canJump == true)
{
staminaBarDisplay -= 0.2;
Wait();
}
if(canJump == false)
{
jumpTimer -= Time.deltaTime;
chMotor.jumping.enabled = false;
}
if(jumpTimer <= 0)
{
canJump = true;
chMotor.jumping.enabled = true;
jumpTimer = 0.7;
}
//if(staminaBarDisplay <= 0.05)
//{
//canJump = false;
//chMotor.jumping.enabled = false;
//}
//else
//{
//canJump = true;
//chMotor.jumping.enabled = true;
//}
if(staminaBarDisplay >= 1)
{
staminaBarDisplay = 1;
}
if(staminaBarDisplay <= 0)
{
staminaBarDisplay = 0;
canJump = false;
chMotor.jumping.enabled = false;
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
}
}
function CharacterDeath()
{
Application.LoadLevel("SIMPLELEVEL");
}
function Wait()
{
yield WaitForSeconds(0.1);
canJump = false;
}
Here is the code. I don't know how to control the features of the class CharacterMotor, because i think that class was replaced by RygidbodyFirstPersonController.
In the standard controller there is no isJumping variable, but what you can do is set JumpForce = 0 instead for the same effect.
Or you can easily add code for this, in RigidbodyFirstPersonController.cs add some bool value isJumping, and then in Update function make sure to set m_Jump = true only if isJumping is true.
There is a section named JUMPING SECTION. That code controls the jump function. If you want to make some changes, just change this section.

unity3d(2d!) translate a point between two cameras

I have a script which limits camera movement to within a defined range. Unfortunately, it only works on the first camera, and there are up to four orthographic cameras in my game.
I have been unable to adapt the script to work with multiple cameras, so I figured that the next best this would be to translate the points from the four corners from the first camera's viewport to world position, then from the world position back to the viewport of cameras 2, 3 and 4. However this doesn't appear to be working.
SpriteRenderer spriteBounds = GameObject.Find("Map").GetComponentInChildren<SpriteRenderer>();
float leftBound =0;
float rightBound =0;
float bottomBound =0;
float topBound = 0;
if((trackPlayer1 == null))
{
camPlayer1.transform.position = this.transform.position;
}
else
{
float vertExtent = camPlayer1.orthographicSize;
float horzExtent = vertExtent * (Screen.width * (camPlayer1.rect.width * 2)) / Screen.height; //I guess the problem is here... but how do I fix this??
leftBound = (float)(horzExtent - spriteBounds.sprite.bounds.size.x / 2.0f);
rightBound = (float)(spriteBounds.sprite.bounds.size.x / 2.0f - horzExtent);
bottomBound = (float)(vertExtent - spriteBounds.sprite.bounds.size.y / 2.0f);
topBound = (float)(spriteBounds.sprite.bounds.size.y / 2.0f - vertExtent);
camPlayer1.transform.position = new Vector3(Mathf.Clamp(trackPlayer1.transform.position.x, leftBound, rightBound), Mathf.Clamp(trackPlayer1.transform.position.y, bottomBound, topBound), camPlayer1.transform.position.z);
}
if((trackPlayer2 == null))
{
camPlayer2.transform.position = this.transform.position;
}
else
{
leftBound = camPlayer1.ViewportToWorldPoint(new Vector3(leftBound, 0, 0)).x;
rightBound = camPlayer1.ViewportToWorldPoint(new Vector3(rightBound, 0, 0)).x;
bottomBound = camPlayer1.ViewportToWorldPoint(new Vector3(0, bottomBound, 0)).y;
topBound = camPlayer1.ViewportToWorldPoint(new Vector3(0, topBound, 0)).y;
leftBound = camPlayer2.WorldToViewportPoint(new Vector3(leftBound, 0, 0)).x;
rightBound = camPlayer2.WorldToViewportPoint(new Vector3(rightBound, 0, 0)).x;
bottomBound = camPlayer2.WorldToViewportPoint(new Vector3(0, bottomBound, 0)).y;
topBound = camPlayer2.WorldToViewportPoint(new Vector3(0, topBound, 0)).y;
camPlayer2.transform.position = new Vector3(Mathf.Clamp(trackPlayer2.transform.position.x, leftBound, rightBound), Mathf.Clamp(trackPlayer2.transform.position.y, topBound, bottomBound), camPlayer2.transform.position.z);
}

Increase speed levels and spawn rate of each kind of Enemies after certain level

I have a unity game script that I want to improve but my basic C terms are making errors.
I want to increase the amount of different Enemy sprites, and include 3 or 4 levels of difficulty by increasing speed and spawn rate for each kind of different enemy sprite after every 3 or 4 levels.
I used
public GameObject enemy;
public GameObject enemy2;
public GameObject enemy3;
// Update is called once per frame
void Update()
{
// Handle the back button on Windows Phone 8
if (Input.GetKeyDown(KeyCode.Escape))
{
HandleBackbutton();
}
spawnNewEnemyTimer -= Time.deltaTime;
if (spawnNewEnemyTimer <= 0)
{
spawnNewEnemyTimer = 5;
int spawnNumberOfEnemies = 1 + (level/2);
for (int i = 0; i < spawnNumberOfEnemies; i++)
{
GameObject enemyToSpawn;
enemyToSpawn = enemy;
if (level > 2)
{
float rndEnemy = Random.Range(0.0f, 1.0f);
if (rndEnemy > 0.5)
{
enemyToSpawn = enemy;
}
else
{
enemyToSpawn = enemy2;
}
else
{
enemyToSpawn = enemy3; //GIVING ME ERROR HERE
}
}
float modifier = Random.Range(-1.0f, 1.0f) * 3;
Instantiate(enemyToSpawn, new Vector3(player.transform.position.x + 20.0f + i * 3,
player.transform.position.y + modifier, 0.0f), Quaternion.identity);
}
float rndPowerupHp = Random.Range(0.0f, 1.0f);
if (rndPowerupHp < 0.1)
{
Instantiate(hpPowerUp, new Vector3(player.transform.position.x + 30.0f,
player.transform.position.y, 0.0f), Quaternion.identity);
}
float rndBuilding = Random.Range(0.0f, 1.0f);
if (rndPowerupHp < 0.5)
{
GameObject whatBuilding = building1;
float rndWhatBulding = Random.Range(0.0f, 1.0f);
if (rndWhatBulding > 0.5)
{
whatBuilding = building1;
}
else
{
whatBuilding = building2;
}
Instantiate(whatBuilding, new Vector3(player.transform.position.x + 30.0f,
0.0f, 0.005f), Quaternion.identity);
}
}
But it's giving me errors.
The problem is more than likely caused by your improper indentation. This causes you to make an error where it concerns braces:
This section of code
if (level > 2)
{
float rndEnemy = Random.Range(0.0f, 1.0f);
if (rndEnemy > 0.5)
{
enemyToSpawn = enemy;
}
else
{
enemyToSpawn = enemy2;
}
else
{
enemyToSpawn = enemy3; //GIVING ME ERROR HERE
}
}
when properly indented looks like this:
if (level > 2)
{
float rndEnemy = Random.Range(0.0f, 1.0f);
if (rndEnemy > 0.5)
{
enemyToSpawn = enemy;
}
else
{
enemyToSpawn = enemy2;
}
else
{
enemyToSpawn = enemy3; //GIVING ME ERROR HERE
}
}
That should make the error pretty obvious. You have a second else statement after your initial one. And that won't fly.
So make sure to always keep a check on your indentation. That will help you prevent or identify errors like this.

OpenGl rendering in iOS

In my project i have to rotate an OBJ file. i have constant pivot point. i got the horizontal rotation exactly.now i have to rotate my OBJ file as vertically. i concluded that have to change angle itself. give ideas to rotate vertically in that constant Pivot point.
my Pivot point is teapotNode_.rotationAxis = CC3VectorMake(0.1, 1, 0.3);
-(void)rightButtonPressed {
float angle;
teapotNode_.rotationAxis = CC3VectorMake(0.1, 1, 0.3);
angle +=2.0;
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}
-(void)leftButtonPressed {
float angle;
teapotNode_.rotationAxis = CC3VectorMake(0.1, 1, 0.3);
angle -=2.0;
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}
-(void)topButtonPressed {
float angle;
teapotNode_.rotationAxis = CC3VectorMake(0.1, 0, 0); ***//changed the Pivot point.***
angle +=2.0; **//how to calculate the Top Down angle.**
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}
I found answer myself https://github.com/antonholmquist/rend-ios in this rend-ios project.
Actually the problem is while clicking the right and left button the rotation is working properly, like top and bottom rotation is also working properly. but when i click right to top / bottom, the object is rotating but it flickered.
The solution is:
Globally declared:
float x=0.0;
float y=0.0;
float z=0.0;
float angle;
float xangle;
float yangle;
-(void)rightButtonPressed {
x=0; y=1; z=0; //ROTATE OBJECT IN Y-AXIS(Y=1 & X=0)
yAngle+=2.0; //GET ANGLE OF OBJECT ROTATION IN Y-AXIS (ANTI CLOCKWISE)
angle +=2.0;
teapotNode_.rotationAxis = CC3VectorMake(x,y,z);
teapotNode_.rotation = CC3VectorMake(0, yAngle, 0);
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}
-(void)leftButtonPressed {
x=0; y=1; z=0; //ROTATE OBJECT IN Y-AXIS(Y=1 & X=0)
yAngle-=2.0; //GET ANGLE OF OBJECT ROTATION IN Y-AXIS (CLOCKWISE)
angle -=2.0;
teapotNode_.rotationAxis = CC3VectorMake(x,y,z);
teapotNode_.rotation = CC3VectorMake(0, yAngle, 0);
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}
-(void)topButtonPressed {
//Existing
/*float angle;
teapotNode_.rotationAxis = CC3VectorMake(0.1, 0, 0); //Changed the Pivot point.
angle +=2.0; //how to calculate the Top Down angle.
*/
//Modified
x=1; y=0; z=0; //ROTATE OBJECT IN Y-AXIS(Y=0 & X=1)
xAngle+=2.0; //GET ANGLE OF OBJECT ROTATION IN Y-AXIS (Top Down)
angle +=2.0;
teapotNode_.rotationAxis = CC3VectorMake(x,y,z);
teapotNode_.rotation = CC3VectorMake(xangle, 0, 0);
director_.running = YES;//Redirector object
if (director_.frameInterval == 2)
{
director_.running = NO;
}
}

smooth camera rotation

Ok im new to javascript and Unity so this is clearly a very noob beginner question.
Basically I have created a script that i place on my camera. Then when i select a model in the game it becomes the target of the camera script and im trying to make the camera smoothly turn to it. below is what im trying
in the update function i use raycast to catch a unit on the mouse click. this becomes the target variable in the script. it sets a bool to true then to follow target in the moveto function. but it only seems to move the camera if i keep the mouse left button pressed down on the unit. Im trying to select a unit then let the camera smoothly rotate to the unit.
Any ideas on this rookie mistake?
#pragma strict
var speed = 5.0;
var freeMovementTurnSpeed = 10.0;
var freeMovementForwardSpeed = 10.0;
var freeMovementVerticalSpeed = 10.0;
var maxHeight = 30;
var minHeight = 2;
var target : Transform;
var distance = 10.0;
var maxDistance = 50;
var minDistance = 10;
var xSpeed = 250.0;
var ySpeed = 120.0;
var yMinLimit = -20;
var yMaxLimit = 80;
private var x = 0.0;
private var y = 0.0;
// The distance in the x-z plane to the target
var followDistance = 30.0;
var maxDistanceDelta = 0.2;
var damping = 3.0;
var followTarget = false;
var smoothRotation ;
function Start () {
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
if(target){
transform.LookAt(target);
}
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
function LateUpdate () {
if(target){
if(followTarget){
moveTo();
}
else{
targetSelectedMovement();
}
}
else {
freeMovement();
}
}
function moveTo(){
//transform.LookAt (target);
var currentDistance = Vector3.Distance(transform.position,target.position);
//if (currentDistance<40){
//followTarget = false;
//}
//else{
smoothRotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, smoothRotation, Time.deltaTime * damping);
print(target);
//transform.position = Vector3.MoveTowards(transform.position,target.position,maxDistanceDelta);
//}
}
function freeMovement(){
var zPos = Input.GetAxis("Vertical") * Time.deltaTime * freeMovementForwardSpeed;
var xPos = Input.GetAxis("Horizontal") * Time.deltaTime * freeMovementTurnSpeed;
var strafePos = Input.GetAxis("Strafe")* Time.deltaTime * freeMovementForwardSpeed;
var vertPos = Input.GetAxis("GainVertical")* Time.deltaTime * freeMovementVerticalSpeed;
if (Input.GetButton("Fire2")) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation2 = Quaternion.Euler(y, x, 0);
transform.rotation = rotation2;
}
else {
transform.Rotate(0, Input.GetAxis("Horizontal")*freeMovementTurnSpeed*Time.deltaTime, 0,Space.World);
}
if (vertPos > 0 && transform.position.y > maxHeight){
vertPos = 0;
}
else if(vertPos < 0 && transform.position.y < minHeight){
vertPos = 0;
}
print(transform.position.y);
transform.Translate(strafePos,vertPos,zPos);
}
function targetSelectedMovement() {
if(Input.GetKey("a") || Input.GetKey("d") ){
x += (-Input.GetAxis("Horizontal")) * xSpeed * 0.02;
var rotation = Quaternion.Euler(y, x, 0);
var currentDistance = Vector3.Distance(transform.position,target.position);
var position = rotation * Vector3(0.0, 0.0, -currentDistance) + target.position;
transform.rotation = rotation;
transform.position = position;
}
var zPos = Input.GetAxis("Vertical") * Time.deltaTime * speed;
currentDistance = Vector3.Distance(transform.position,target.position);
if(currentDistance < maxDistance && zPos < 0){
transform.Translate(0, 0, zPos);
}
else if(currentDistance > minDistance && zPos > 0){
transform.Translate(0, 0, zPos);
}
if (Input.GetButton("Fire2")) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation2 = Quaternion.Euler(y, x, 0);
var currentDistance2 = Vector3.Distance(transform.position,target.position);
var position2 = rotation2 * Vector3(0.0, 0.0, -currentDistance2) + target.position;
transform.rotation = rotation2;
transform.position = position2;
}
}
static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
function Update () {
var hit : RaycastHit;
if (Input.GetButton("Fire1")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Cast a ray forward from our position for the specified distance
if (Physics.Raycast(ray, hit))
{
// Add a specified force to the Rigidbody component to the other GameObject
if(hit.collider.tag == "Unit"){
print("Selected " + hit.collider.gameObject.name);
target = hit.collider.gameObject.transform;
//transform.LookAt(target);
followTarget = true;
}
else {
target = null;
}
}
}
}
:)
Answer pulled from my comments above:
"I'll have to look when I get on my dev. machine but in the mean time try replacing Input.GetButton("Fire1") with Input.GetButtonDown("Fire1"). Just as a test, because looking at your code nothing jumps out at me. GetButton is true as long as the button is held, in the past I have had issues with it incorrectly triggering just as the mouse moved off an object."