How can I make this movement relative to my camera direction - c#

I need to move my target object in world space relative to the direction the main camera is facing but only on the x&z axis and relative to the my player on the on the y axis.
Any guidance is greatly appreciated.
public class test : MonoBehaviour {
public string raise = "Raise";
public string lower = "Lower";
public string left = "Left";
public string right = "Right";
public string closer = "Closer";
public string further = "Further";
public GameObject target;
private float xPos;
private float yPos;
private float zPos;
// Use this for initialization
void Start () {
xPos = target.transform.position.x;
yPos = target.transform.position.y;
zPos = target.transform.position.z;
}
void FixedUpdate () {
Vector3 currPos = target.transform.position;
Vector3 nextPos = new Vector3 (xPos, yPos, zPos);
target.GetComponent < Rigidbody > ().velocity = (nextPos - currPos) * 10;
if (Input.GetButton (raise)) {
print ("Moving Up");
yPos = yPos + 0.05f;
}
if (Input.GetButton (lower)) {
print ("Moving Down");
yPos = yPos - 0.05f;
}
if (Input.GetButton (left)) {
print ("Moving Left");
xPos = xPos - 0.05f;
}
if (Input.GetButton (right)) {
print ("Moving Right");
xPos = xPos + 0.05f;
}
if (Input.GetButton (closer)) {
print ("Moving Closer");
zPos = zPos - 0.05f;
}
if (Input.GetButton (further)) {
print ("Moving Further");
zPos = zPos + 0.05f;
}
}

You can get the camera's direction like this:
var camDir = Camera.main.transform.forward;
You only want the x/y component, so we're going to renormalise that vector:
camDir.y = 0;
camDir.Normalized();
That's the forward vector. Because it's effectively a 2D vector now, we can get the cam's right-hand vector easily:
var camRight = new Vector3(camDir.z, 0f, -camDir.x);
I'm going to assum your player's up direction is just up the y axis. If it's different, sub in that vector:
var playerUp = Vector3.up;
Now, in your sample you're doing manual integration, then passing it off to the rigid body system to do integration again. Let's just work out our own velocity directly:
var newVel = Vector3.zero;
if (/*left*/) newVel -= camRight * 0.05;
if (/*right*/) newVel += camRight * 0.05;
if (/*closer*/) newVel -= camDir * 0.05;
if (/*farter*/) newVel += camDir * 0.05;
if (/*raise*/) newVel += playerUp * 0.05;
if (/*lower*/) newVel -= playerUp * 0.05;
Change that 0.05 if you want to move faster or more slowly. You can do lots of stuff here to make controls feel really nice, like having a little deadzone or feeding directly off analogue input rather than buttons.
Then finally commit that into the rigid body:
target.GetComponent<Rigidbody>().velocity = newVel;

Related

Variable not assigning on void Start() (noob question)

I have a code to make a cube move back and forth within a certain range of it's original placed position.
The script is directly on the cube and it does move, but around 0,0,0 coordinates, not it's original position.
Here is my code:
using UnityEngine;
public class ObstacleResonator : MonoBehaviour
{
public float xspeed = 0f;
public float yspeed = 0f;
public float zspeed = 0f;
public float xrange = 0f;
public float yrange = 0f;
public float zrange = 0f;
float StartX;
float StartY;
float StartZ;
Vector3 desiredPosition;
void Start()
{
// this is what i think is the problem, the variables are not getting assigned
float StartX = transform.position.x;
float StartY = transform.position.y;
float StartZ = transform.position.z;
}
// Update is called once per frame
void Update()
{
// the following is to make it reverse once it is out of range in any of the axes
if (transform.position.x > xrange + StartX)
{
xspeed = -xspeed;
}
if (transform.position.x < -xrange + StartX)
{
xspeed = -xspeed;
}
if (transform.position.y > yrange + StartY)
{
yspeed = -yspeed;
}
if (transform.position.y < -yrange + StartY)
{
yspeed = -yspeed;
}
if (transform.position.z > zrange + StartZ)
{
zspeed = -zspeed;
}
if (transform.position.z < -zrange + StartZ)
{
zspeed = -zspeed;
}
// the following actually moves the cube
desiredPosition.x = transform.position.x + xspeed * Time.deltaTime;
desiredPosition.y = transform.position.y + yspeed * Time.deltaTime;
desiredPosition.z = transform.position.z + zspeed * Time.deltaTime;
transform.position = desiredPosition;
}
}
There probably is a more compact way to write it.
The cube is moving around 0,0,0 instead of it's original transform position. I tried assigning the StartX, StartY, StartZ values manually, and it worked perfectly, but they just dont seem to get assigned by on the start.
The problem is that you declare NEW variables within the Start() function, they go out of scope as soon as the function is executed. You don't update the class variables.
Use this instead:
void Start()
{
StartX = transform.position.x;
StartY = transform.position.y;
StartZ = transform.position.z;
}

How to scale and rotate a sprite between two points based on distance

I am working on a project in unity and I have a small circle that shows how much power will be applied to a ball and an arrow that shows the direction.
The circle and arrow are meant to scale up to a max distance; the arrow scales but it is too big (takes up half the screen) and doesn't rotate properly; the circle does not scale at all. I have tried to change the local scale of the arrow and messed around with the various values but I am not sure what to really do. The arrow tends to only face the correct direction when the cursor is in the top left and the arrow is in the bottom right.
The two points, point A and B are two empty objects; point B is attached to the ball and pointA follows the mouse. When the ball is clicked on and the cursor is dragged away pointB moves in the opposite direction; I am trying to get the arrow to face pointB at all times or point at pointB from the opposite side of the ball.
Everything except for the arrow and circle rotating and scaling works. I'm fairly new to code and don't understand Mathf.Log. The arrow rotate and scale code is commented out as I am currently trying to get the circle to work.
If you can point me in the right direction or help with just one of these issues I'd greatly appreciate it.
public class PlayerBallHit : MonoBehaviour
{
private GameObject mousePointA;
private GameObject mousePointB;
private GameObject arrow;
private GameObject circle;
// calc distance
private float currDistance;
public float maxDistance = 3f;
private float spaceLimit;
private float shootPower;
public float shootPowervar;
public Vector2 shootDirection;
void Start()
{
}
void Awake()
{
mousePointA = GameObject.FindGameObjectWithTag("PointA");
mousePointB = GameObject.FindGameObjectWithTag("PointB");
arrow = GameObject.FindGameObjectWithTag("Stick");
circle = GameObject.FindGameObjectWithTag("Circle");
}
private void OnMouseDrag()
{
currDistance = Vector2.Distance(mousePointA.transform.position, transform.position);
if (currDistance <= 3f)
{
spaceLimit = currDistance;
}
else
{
spaceLimit = maxDistance;
}
// Direction of Hit and Circle
StrDirMarkers();
// calc Power & Direction
shootPower = Mathf.Abs(spaceLimit) * shootPowervar;
Vector3 dimxy = mousePointA.transform.position - transform.position;
float difference = dimxy.magnitude;
mousePointB.transform.position = (Vector3)transform.position + ((dimxy / difference) * currDistance * -1);
mousePointB.transform.position = new UnityEngine.Vector3(mousePointB.transform.position.x, mousePointB.transform.position.y);
shootDirection = (Vector2)Vector3.Normalize(mousePointA.transform.position - transform.position);
}
void OnMouseUp()
{
//arrow.GetComponent<SpriteRenderer>().enabled =false;
circle.GetComponent<SpriteRenderer>().enabled = false;
Vector2 push = shootDirection * shootPower *-1;
GetComponent<Rigidbody2D>().AddForce(push, ForceMode2D.Impulse);
}
private void StrDirMarkers()
{
//arrow.GetComponent<SpriteRenderer>().enabled = true;
circle.GetComponent<SpriteRenderer>().enabled = true;
// calc position
/*
if (currDistance <= maxDistance)
{
arrow.transform.position = new Vector2((2f * transform.position.x) - mousePointA.transform.position.x, (2f * transform.position.y) - mousePointA.transform.position.y);
}
else
{
Vector2 dimxy = mousePointA.transform.position - transform.position;
float difference = dimxy.magnitude;
arrow.transform.position = (Vector2)transform.position + ((dimxy / difference) * maxDistance * -1);
arrow.transform.position = new UnityEngine.Vector2(arrow.transform.position.x, arrow.transform.position.y);
}
*/
circle.transform.position = transform.position + new Vector3(0, 0, 0.04f);
Vector3 dir = mousePointA.transform.position - transform.position;
float rot;
if(Vector3.Angle(dir, transform.forward)> 90)
{
rot = Vector3.Angle(dir, transform.right);
}else
{
rot = Vector3.Angle(dir, transform.right) * -1;
}
//arrow.transform.eulerAngles = new Vector3(0, 0, rot);
// scale arrow
float scaleX = Mathf.Log(1 + spaceLimit / 10000f, 2f) * 0.05f;
float scaleY = Mathf.Log(1 + spaceLimit / 10000f, 2f) * 0.05f;
//arrow.transform.localScale = new Vector3(1 + scaleX, 1 + scaleY, 0.001f);
circle.transform.localScale = new Vector3(1 + scaleX, 1 + scaleY, 0.001f);
}
}
try to use this code for scaling and rotate the arrow
Vector3 dir = mousePointA.transform.position - transform.position;
float rot;
if (mousePointA.transform.position.y >= transform.position.y)
{
rot = Vector3.Angle(dir, transform.position) * -1;
}
else
{
rot = Vector3.Angle(dir, transform.position);
}
arrow.transform.eulerAngles = new Vector3(0, 0, rot);
// scale arrow
float scaleValue = Vector3.Distance(mousePointA.transform.position,
transform.position);
arrow.transform.localScale = new Vector3(1 + scaleValue,
arrow.transform.localScale.y, 1);
circle.transform.localScale = new Vector3(1 + scaleValue * 0.05f, 1 + scaleValue *
0.05f, 0.001f);

How to Rotate an Object Based On Swipe

I am working on a script to move an object back anf forth based on swipe similarly to a game called Sky Rusher on the iOS App Store. The movement in the original game lets you swipe in any direction and an object moves in the same direction. However, the object also "bounces" for lack of a better term. For example, if you swipe to the left, the object will tilt to the left and then tilt back to its original position. For the best example I can give, please take a look at this video for a demonstartion of the game:
Sky Rusher Gameplay
This is the code I currently have (the object also doesn't move back and forth when swiping, not sure what==y that is but have an idea on how to fix it):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovePlayer : MonoBehaviour
{
private Vector3 currentPos;
private Vector3 touchPos;
private float screenWidth;
private float screenHeight;
private float touchX;
private float touchY;
private float objectX;
private float objectY;
// Start is called before the first frame update
void Start()
{
touchX = 0;
touchY = 0;
screenWidth = (float)Screen.width / 2.0f;
screenHeight = (float)Screen.height / 2.0f;
currentPos = new Vector3(0.0f, 1.0f, 0.0f);
}
// Update is called once per frame
void Update()
{
if(Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
//touchPos = new Vector3((touch.position.x - screenWidth)/screenWidth, (touch.position.y - screenHeight)/screenHeight + 1, 0.0f);
touchPos = new Vector3(touch.position.x, touch.position.y, 0.0f);
touchX = (touchPos.x - screenWidth)/screenHeight - 1f;
touchY = (touchPos.y - screenHeight)/screenHeight + 1f;
//objectX = ((currentPos.x * screenWidth) - screenWidth)/screenWidth;
//objectY = ((currentPos.y * screenHeight) - screenHeight)/screenHeight;
objectX = currentPos.x;
objectY = currentPos.y;
objectX += (touchX - objectX) * 1.5f;
//objectY += (touchY - objectY) * 1.5f;
if(touchX >= 0.9f)
{
objectX+=0.05f;
}
else if(touchX <= -0.9f)
{
objectX-=0.05f;
}
currentPos = new Vector3(objectX, objectY, 0.0f);
transform.position = currentPos;
}
}
}
void OnGUI()
{
/*
// Compute a fontSize based on the size of the screen width.
GUI.skin.label.fontSize = (int)(Screen.width / 40.0f);
GUI.Label(new Rect(20, 20, screenWidth, screenHeight * 0.25f),
"Pos: x = " + (objectX.ToString("f2")) +
", y = " + objectY.ToString("f2"));
GUI.Label(new Rect(20, 50, screenWidth, screenHeight * 0.25f),
"Touch: x = " + (touchX.ToString("f2")) +
", y = " + (touchY.ToString("f2")));
*/
}
}
I need my object to tilt when moved similarly to how it is done in sky rusher. My game is played in a landscape orientation on an iOS Device using Unity Remote 5 and Unity 2018.3.
Quick way to achieve this effect, if I understood correctly what you mean:
1) Each time touchX >= .9f (you are moving right) apply localRotation along Z axis with some angle.
2) Each time touchX <= -.9f (you are moving left) apply localRotation along Z axis with some negative angle.
To make this look smooth and not jumpy, apply rotation along several frames, first calculating target rotation, then using RotateTowards with some given speed. Here is yourr code slightly modified:
public float tiltEffectAngle = 20;
public float tiltEffectSpeed = 90f;
void Update() {
var targetRotation = Quaternion.identity;
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved) {
//touchPos = new Vector3((touch.position.x - screenWidth)/screenWidth, (touch.position.y - screenHeight)/screenHeight + 1, 0.0f);
touchPos = new Vector3(touch.position.x, touch.position.y, 0.0f);
touchX = (touchPos.x - screenWidth) / screenHeight - 1f;
touchY = (touchPos.y - screenHeight) / screenHeight + 1f;
//objectX = ((currentPos.x * screenWidth) - screenWidth)/screenWidth;
//objectY = ((currentPos.y * screenHeight) - screenHeight)/screenHeight;
objectX = currentPos.x;
objectY = currentPos.y;
objectX += (touchX - objectX) * 1.5f;
//objectY += (touchY - objectY) * 1.5f;
if (touchX >= 0.9f) {
objectX += 0.05f;
targetRotation = Quaternion.Euler(
transform.localEulerAngles.x,
transform.localEulerAngles.y,
tiltEffectAngle);
} else if (touchX <= -0.9f) {
objectX -= 0.05f;
targetRotation = Quaternion.Euler(
transform.localEulerAngles.x,
transform.localEulerAngles.y,
-tiltEffectAngle);
}
currentPos = new Vector3(objectX, objectY, 0.0f);
transform.position = currentPos;
}
}
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, targetRotation, tiltEffectSpeed * Time.deltaTime);
}

Rotate my Object with Mouse and Touch (Unity, C#)

I have a Problem that I just discovered a few days ago and the Problem is that I cant rotate my Object on a Surface with Touch because I only can Rotate it via Mouse and my question is what do I have to add to my Simple Mouse Roatator Script?
Im a beginner with C# and Unity so hopefully somebody could help me here.
Here is the Code:
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Utility
{
public class SimpleMouseRotator_E : MonoBehaviour
{
// A mouselook behaviour with constraints which operate relative to
// this gameobject's initial rotation.
// Only rotates around local X and Y.
// Works in local coordinates, so if this object is parented
// to another moving gameobject, its local constraints will
// operate correctly
// (Think: looking out the side window of a car, or a gun turret
// on a moving spaceship with a limited angular range)
// to have no constraints on an axis, set the rotationRange to 360 or greater.
public Vector2 rotationRange = new Vector3(70, 70);
public float rotationSpeed = 10;
public float dampingTime = 0.2f;
public bool autoZeroVerticalOnMobile = true;
public bool autoZeroHorizontalOnMobile = false;
public bool relative = true;
public GameObject reflectionprobe;
public Vector2 startPos;
public Vector2 direction;
public bool directionChosen;
private Vector3 m_TargetAngles;
private Vector3 m_FollowAngles;
private Vector3 m_FollowVelocity;
private Quaternion m_OriginalRotation;
private bool whileDragging;
private void Start()
{
whileDragging = false;
m_OriginalRotation = transform.localRotation;
}
private void Update()
{
// Track a single touch as a direction control.
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
// Handle finger movements based on touch phase.
switch (touch.phase)
{
// Record initial touch position.
case TouchPhase.Began:
startPos = touch.position;
directionChosen = false;
break;
// Determine direction by comparing the current touch position with the initial one.
case TouchPhase.Moved:
direction = touch.position - startPos;
break;
// Report that a direction has been chosen when the finger is lifted.
case TouchPhase.Ended:
directionChosen = true;
break;
}
}
if (directionChosen)
{
// Something that uses the chosen direction...
}
if (whileDragging)
{
// we make initial calculations from the original local rotation
transform.localRotation = m_OriginalRotation;
// read input from mouse or mobile controls
float inputH;
float inputV;
if (relative)
{
inputH = CrossPlatformInputManager.GetAxis("Mouse X");
inputV = CrossPlatformInputManager.GetAxis("Mouse Y");
// wrap values to avoid springing quickly the wrong way from positive to negative
if (m_TargetAngles.y > 180)
{
m_TargetAngles.y -= 360;
m_FollowAngles.y -= 360;
}
if (m_TargetAngles.x > 180)
{
m_TargetAngles.x -= 360;
m_FollowAngles.x -= 360;
}
if (m_TargetAngles.y < -180)
{
m_TargetAngles.y += 360;
m_FollowAngles.y += 360;
}
if (m_TargetAngles.x < -180)
{
m_TargetAngles.x += 360;
m_FollowAngles.x += 360;
}
#if MOBILE_INPUT
// on mobile, sometimes we want input mapped directly to tilt value,
// so it springs back automatically when the look input is released.
if (autoZeroHorizontalOnMobile) {
m_TargetAngles.y = Mathf.Lerp (-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f);
} else {
m_TargetAngles.y += inputH * rotationSpeed;
}
if (autoZeroVerticalOnMobile) {
m_TargetAngles.x = Mathf.Lerp (-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f);
} else {
m_TargetAngles.x += inputV * rotationSpeed;
}
#else
// with mouse input, we have direct control with no springback required.
m_TargetAngles.y += inputH * rotationSpeed;
m_TargetAngles.x += inputV * rotationSpeed;
#endif
// clamp values to allowed range
m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y * 0.5f, rotationRange.y * 0.5f);
m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x * 1f, rotationRange.x * 0.2f);
}
else
{
inputH = -Input.mousePosition.x;
inputV = -Input.mousePosition.y;
// set values to allowed range
m_TargetAngles.y = Mathf.Lerp(-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH / Screen.width);
m_TargetAngles.x = Mathf.Lerp(-rotationRange.x * 1f, rotationRange.x * 1f, inputV / Screen.height);
}
// smoothly interpolate current values to target angles
m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime);
// update the actual gameobject's rotation
transform.localRotation = m_OriginalRotation * Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0);
}
}
public void BeginDrag()
{
whileDragging = true;
}
public void EndDrag()
{
whileDragging = false;
}
}
}
Maybe somebody could help me here it would be pretty awesome!
Grettings from Germany
Hmmm, why not try using this?
float rotSpeed = 20;
void OnMouseDrag(){
float rotX = Input.GetAxis("Mouse X") * rotSpeed * Mathf.Deg2Rad;
float rotY = Input.GetAxis("Mouse Y") * rotSpeed * Mathf.Deg2Rad;
transform.RotateAround(Vector3.up, -rotX);
transform.RotateAround(Vector3.right, rotY);
}
A simple way of rotating using touch input :)

How can i make equal spaces between the squad members in the circle formation?

When it's square formation i can set the space fine.
But i'm not sure how to do it with the circle formation.
Inside the FormationSquare method i'm using the space variable for the square formation. Now i need to do the same idea for the circle formation too.
Maybe inside the RandomCircle to change something and using the space variable ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle
}
public Transform squadMemeber;
public int columns = 4;
public int space = 10;
public int numObjects = 20;
public float yOffset = 1;
private Formation formation;
// Use this for initialization
void Start()
{
formation = Formation.Square;
ChangeFormation();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
GameObject[] objects = GameObject.FindGameObjectsWithTag("Squad Member");
if (objects.Length > 0)
{
foreach (GameObject obj in objects)
Destroy(obj);
}
ChangeFormation();
}
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
for (int i = 0; i < 23; i++)
{
Transform go = Instantiate(squadMemeber);
Vector3 pos = FormationSquare(i);
go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
go.Rotate(new Vector3(0, -90, 0));
go.tag = "Squad Member";
}
formation = Formation.Circle;
break;
case Formation.Circle:
Vector3 center = transform.position;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = RandomCircle(center, 5.0f);
var rot = Quaternion.LookRotation(center - pos);
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
Transform insObj = Instantiate(squadMemeber, pos, rot);
insObj.rotation = rot;
insObj.tag = "Squad Member";
}
formation = Formation.Square;
break;
}
}
Vector2 FormationSquare(int index) // call this func for all your objects
{
float posX = (index % columns) * space;
float posY = (index / columns) * space;
return new Vector2(posX, posY);
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
}
The issue here is that your RandomCircle() method is...well, random. You're just arbitrarily grabbing an angle around the circle, without any regard for where other squad members have been placed, meaning they'll practically never be evenly distributed.
Consider calculating the angle that will separate each squad member (if distributed evenly) beforehand, then perform a similar approach to FormationSquare() where you iterate through the squad to distribute them.
This may be a bit closer to what you want (basing this on the assumption that RandomCircle() already works as designed):
Vector3 FormationCircle(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
To call it, you'd do:
Vector3 center = transform.position;
float radius = (float)space / 2;
float angleIncrement = 360 / (float)numObjects;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = FormationCircle(center, radius, i, angleIncrement);
// ...
}
Hope this helps! Let me know if you have any questions.

Categories

Resources