Unity - How can I add or subtract a chosen number of degrees from an angle? - unity3d

I was wondering if there's a way to add (in my case) 120 degrees everytime I push 'ButtonA', and subtract 120 degrees everytime I push 'ButtonB', from the Z-axis rotation of a 2d sprite (prefab).
This is the code I'm using at the moment, but it only rotates once left, and once right:
function TouchOnScreen ()
{
if (Input.touchCount > 0)
{
var touch = Input.touches[0];
if (touch.position.x < Screen.width/2)
{
var RSpeed = 10.0f
transform.rotation = Quaternion.Lerp ( transform.rotation,Quaternion.Euler(0,0,120), Time.deltaTime*RSpeed);
Debug.Log("RotateRight");
}
else if (touch.position.x > Screen.width/2)
{
var LSpeed = 10.0f
transform.rotation = Quaternion.Lerp ( transform.rotation,Quaternion.Euler(0,0,-120), Time.deltaTime*LSpeed);
Debug.Log("RotateLeft");
}
}
}
Thanks in advance!
Note: Please use unityscript if you can, I'm pretty new to coding and unityscript is all I know so far.

From the online documentation it is shown that the signature of the function is
static function Lerp(from: Quaternion, to: Quaternion, t: float): Quaternion;
that means the second parameter is the new rotation of the object not the rotation offset
you should use something of the sort
function TouchOnScreen ()
{
if (Input.touchCount > 0)
{
var touch = Input.touches[0];
if (touch.position.x < Screen.width/2)
{
var RSpeed = 10.0f
transform.rotation = Quaternion.Lerp ( transform.rotation,transform.rotation + Quaternion.Euler(0,0,120), Time.deltaTime*RSpeed);
Debug.Log("RotateRight");
}
else if (touch.position.x > Screen.width/2)
{
var LSpeed = 10.0f
transform.rotation = Quaternion.Lerp ( transform.rotation,transform.rotation + Quaternion.Euler(0,0,-120), Time.deltaTime*LSpeed);
Debug.Log("RotateLeft");
}
}
}
note the second parameter is transform.rotation + Quaternion.Euler(0,0,120) (current rotation + offset to the right)
I'm not an expert on unity engine (I only started toying with the free version yesterday, literally)

Try this one
function TouchOnScreen ()
{
if (Input.touchCount > 0)
{
var touch = Input.touches[0];
if (touch.position.x < Screen.width/2)
{
var RSpeed = 10.0f
transform.Rotate(0,0,120);
Debug.Log("RotateRight");
}
else if (touch.position.x > Screen.width/2)
{
var LSpeed = 10.0f
transform.Rotate(0,0,-120);
Debug.Log("RotateLeft");
}
}
}
If this not works try with Gameobject. I didn't check this

Related

How to make panel swiper for canvas that scales with screen size

I created a level menu manager where you swipe from one screen to the next horizontally, and it worked great. Until I realized I had to change the canvas to scale with screen size in order to preserve the layout for various devices. Now, the panels resize. Which is what I want, however it means the swipe no longer works since the panels stretch and thin to accommodate yet their position does not change. They might overlap now, or have big gaps in between. See photo examples. Is there anything I can do? I cannot for the life of me figure out how to calculate where their new position should be based on screen size and move them there using the left and right rect transform properties. It sounds easy but the math just does not math in all my efforts. Been tearing my hair out over this all day.
Code for my page swiper:
public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler
{
private Vector3 panelLocation;
public float percentThreshold = 0.2f;
public float easing = 0.5f;
int currentChild;
Player player;
void Start()
{
player = PlayerData.GetPlayerData();
currentChild = player.lastPanel;
panelLocation = transform.position;
panelLocation += new Vector3(-Screen.width * (currentChild-1), 0, 0);
transform.position = panelLocation;
}
public void OnDrag(PointerEventData data){
float difference = data.pressPosition.x - data.position.x;
if ((currentChild == 9 && difference < 0) || (currentChild == 1 && difference > 0))
{
transform.position = panelLocation - new Vector3(difference, 0, 0);
}
}
public void OnEndDrag(PointerEventData data){
float percentage = (data.pressPosition.x - data.position.x) / Screen.width;
if (Mathf.Abs(percentage) >= percentThreshold){
Vector3 newLocation = panelLocation;
int panelCount = transform.childCount - 1;
if (percentage > 0 && currentChild < panelCount){
newLocation += new Vector3(-Screen.width, 0, 0);
currentChild += 1;
}else if(percentage < 0 && currentChild > 1){
newLocation += new Vector3(Screen.width, 0, 0);
currentChild -= 1;
}
transform.position = newLocation;
panelLocation = newLocation;
} else {
transform.position = panelLocation;
}
}
}
Before, right next to each other for perfect swipe:
After example 1, wider screen size:
After example 2, thinner screen size:

How to check rotation of an object in Unity3d?

I'm a unity3d learner. I have a problem with rotation of an object. I want to rotate objects about 40 degrees along the z axis. If the objects rotation has reached 40 degrees, I want something to happen. Here is my code.
foreach(Touch touch in Input.touches) {
if(touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled) {
var target = Quaternion.Euler (0, 0,-40);
transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);
if (transform.rotation.eulerAngles.z == -40) {
toggle = true;
speech = "blah blah blah";
snake = man;
}
}
}
The if(transform.rotation.eulerAngles.z == -40) line of code is not working. So I don't know if the rotation degree has reached 40 degree or not. How do I check if the rotation degree has reached 40 degrees?
I don't understand your code intent.
EulerAngles is not set negative only positive value(Vector3)
-if(eulerAngles.z == -40) is not work you try change value -40 -> 320
If you want scenario ontouch -> object rotation -> event
try this code.
float rotTime = 1f; // rotation duration
Vector3 rotValue = new Vector3(0, 0, -40f); // rotation value
void Update () {
foreach (Touch touch in Input.touches)
if (touch.phase == TouchPhase.Began) OnTouchEvent();
}
void OnTouchEvent()
{
StopCoroutine("rotationCoroutine");
StartCoroutine("rotationCoroutine");
}
IEnumerator rotationCoroutine()
{
float startTime = Time.time;
Vector3 startRot = transform.eulerAngles;
Vector3 endRot = startRot;
endRot += rotValue;
while (Time.time - startTime <= rotTime)
{
transform.eulerAngles = Vector3.Slerp(startRot, endRot,(Time.time - startTime) / rotTime);
yield return null; // wait 1 frame
}
//rotation end
MyAction();
}
void MyAction()
{
Debug.Log("rotation end");
//toggle = true;
//speech = "blah blah";
//snake = man;
}
Good Luck :D

MonoGame - Drag and Drop

I am currently writing a game using the monogame framework. I am having trouble with reacting to the touch input correctly. I want the user to be able to drag the "objToDrag". The problem is that both deltaX and deltaY are always zero. Here is my code:
var touchState = TouchPanel.GetState();
foreach (var touch in TouchPanel.GetState())
{
if (touch.State == TouchLocationState.Moved)
{
TouchLocation prevLoc;
if (!touch.TryGetPreviousLocation(out prevLoc)) continue;
float deltaX = touch.Position.X - prevLoc.Position.X;
float deltaY = touch.Position.Y - prevLoc.Position.Y;
this.objToDrag.X += deltaX;
this.objToDrag.Y += deltaY;
}
}
Use the delta value to calculate how far your object should move, no need to calculate your own.
foreach (var touch in TouchPanel.GetState())
{
if (touch.State == TouchLocationState.Moved)
{
TouchLocation prevLoc;
if (!touch.TryGetPreviousLocation(out prevLoc)) continue;
float deltaX = touch.Delta.X;
float deltaY = touch.Delta.Y;
this.objToDrag.X += deltaX;
this.objToDrag.Y += deltaY;
}
}

How to Put this strength meter bar to an object?

#pragma strict
var strengthAmount : float = 0.0F;
private var maxStrengthAmount : float = 100.0F;
var guiSkin : GUISkin;
var barSprite : Texture2D;
var powerButton : GUITexture;
function Update () {
for (var touch : Touch in Input.touches)
{
if (strengthAmount >= 100.0F)
{
strengthAmount = maxStrengthAmount;
// Do stuff here
}
else if (strengthAmount < 0.0F)
{
strengthAmount = 0.0F;
}
if(touch.phase == TouchPhase.Stationary && powerButton.HitTest(touch.position)){
strengthAmount += 1.0F;
}
else if(touch.phase == TouchPhase.Ended && powerButton.HitTest){
strengthAmount = 0.0F;
}
}
}
function OnGUI()
{
GUI.skin = this.guiSkin;
GUI.DrawTexture(new Rect(Screen.width / 8, Screen.height - 167.5F, 150
(strengthAmount / maxStrengthAmount), 31), barSprite);
GUI.Box(new Rect(Screen.width / 8, Screen.height - 167.5F, 150, 31), "Strength");
}
Here is my strength meter bar code, but I want to put it on an object that when I release the button, the object will be thrown away? I am new to Unity3D so please help me how to make a script on that or help me directly thank you
Create a JS script, paste this script and save it. Create a game object, select it, on the inspector click on the button Add component. Then find your script and add it.
Then create another script that has the following:
Update() //this is C#
{
if (GetKeyUp(KeyCode. /*here find the key code of the button that you want to release*/ )
Destroy(this); //if you want to destroy the object
}

iPhone Accelerometer calibration

How do I properly calibrate the accelerometer for my iPhone game? Currently, when the phone is on a flat surface, the paddle drifts to the left. High or Low Pass filters are not an acceptable solution as I need complete control over the paddle even at low & high values. I know Apple has the BubbleLevel sample but I find it difficult to follow... could someone simplify the process?
My accelerometer code looks like this:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
float acelx = -acceleration.y;
float x = acelx*40;
Board *board = [Board sharedBoard];
AtlasSprite *paddle = (AtlasSprite *)[board.spriteManager getChildByTag:10];
if ( paddle.position.x > 0 && paddle.position.x < 480) {
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
if ( paddle.position.x < 55 ) {
paddle.position = ccp(56, paddle.position.y);
}
if ( paddle.position.x > 435 ) {
paddle.position = ccp(434, paddle.position.y);
}
if ( paddle.position.x < 55 && x > 1 ) {
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
if ( paddle.position.x > 435 && x < 0) {
paddle.position = ccp(paddle.position.x+x, paddle.position.y);
}
}
Thank you!
Okay, problem SOLVED and the solution is so simple I'm actually embarrassed I didn't come up with it sooner. It's as simple as this:
In a "Calibration Button":
//store the current offset for a "neutral" position
calibration = -currentAccelX * accelerationFactor;
In the game time accelerometer function:
//add the offset to the accel value
float x = (-acceleration.y * accelerationFactor) + calibration;
It's as simple as adding the offset. * hides his head *
This is the code I have so far:
//calibrate code from StackOverflow
float calibration = -acceleration.x * accelerationFraction;
float x = (-acceleration.y * accelerationFraction) + calibration;
//My original code
accelerationFraction = acceleration.y*2;
if (accelerationFraction < -1) {
accelerationFraction = -1;
} else if (accelerationFraction > 1) {
accelerationFraction = 1;
}
//API CHANGE set delegate to self
if (orientation == UIDeviceOrientationLandscapeLeft){
accelerationFraction *= -1;
}