I'm trying to move my object towards movePoint with the space button through the Input System. The problem I'm having is that the bool I use that is true when I press space is only active for one frame so the distance traveled is very small.
void Update()
{
float movementAmount = speed * Time.deltaTime;
bool snaptoHighlight = playerControls.Player.space.WasPerformedThisFrame();
Debug.Log(snaptoHighlight);
if (snaptoHighlight)
{
//transform.position = movePoint.position;
transform.position = Vector2.MoveTowards(transform.position, movePoint.position, movementAmount);
}
}
If I just use transform.position = movePoint.position the object does move to where I want it to be but it instantly teleports but I am trying to get the moving animation in between the travelling. Is there a way to approach this? thank you
Related
I want to save the initial position of the cursor at start, and after the cursor has been moved and the mouse button is released, it should return to its original position (using 10f * Time.deltaTime), but this does not work
[SerializeField] private Transform cursor;
private Vector3 OriginalPosition;
void Start()
{
OriginalPosition = cursor.transform.position;
Debug.Log(OriginalPosition);
}
void OnMouseUp()
{
Debug.Log("MouseUp");
cursor.transform.position = Vector3.MoveTowards(cursor.position, OriginalPosition, 10f * Time.deltaTime);
}
The problem is that you are assuming that calling a MoveForward will make your game object follow all its way back to the original position, which will not happen, what you're actually doing is saying to your cursor "when I release my mouse button, calculate the direction between my current position and original position and with a speed of 10 units per second move the amount that it would be in 1 frame". What you need is to make the MoveToward operation during the period of N frames, for making this happen you need to use a coroutine, so follow a similar code
public Transform cursor;
public Transform originalPosition;
public void Move()
{
StartCoroutine(MoveToTargetPosition());
IEnumerator MoveToTargetPosition()
{
while (Vector3.Distance(cursor.position, originalPosition.position) >= .5f)
{
yield return null;
cursor.position = Vector3.MoveTowards(cursor.position, originalPosition.position, 10f * Time.deltaTime);
}
}
}
Hope this help
travelTime = 0.0f;
while (Vector3.Distance(Vector2.Lerp(startPos, endPos, travelTime), transform.position) >= maxDistance) {
locationToGo = Vector2.Lerp(startPos, Input.mousePosition, travelTime);
travelTime += 0.1f;
}
// SHOW
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, locationToGo, ref velocity, smoothTime);
So, this code is meant to use Lerp to return a Vector2 a certain amount of 'steps' towards the mouse pointer. And then give that value to the SmoothDamp to move the square to the pos. But the Lerp is not calculating correctly. Does anyone know what is wrong, or any better working alternatives?
Since I don't really know what exactly you are trying to achieve i'm just gonna guess you want to move a GameObject to the MousePosition every Frame.
You could do it like this (it is out of my head, not compileproof):
GameObject ourGameobject;
Vector3 ourTarget;
void Update()
{
ourGameobject.transform.position = Vector3.lerp(ourGameobject.transform.position, ourTarget, Time.DeltaTime);
}
For faster or lower speed just multiply Time.DeltaTime with sth.
Also Note that Input.MousePosition returns a coordinate on the screen.
Good day. I am trying to achieve simple thing but nothing just works....
The desired output:
• Player touches a place in my world
• Character starting to smoothly move with walking animation towards that location
The actual result:
• Player touches a place in my world
• Character just jumps into the final point, no smooth movement nothing
Things tried:
• Vector2 finalPosition = Camera.main.ScreenToWorldPoint(position);
transform.position = finalPosition;
In this scenario the character just jumps into the final point
• Vector2 finalPosition = Camera.main.ScreenToWorldPoint(position);
transform.Translate(finalPosition);
In this case character just dissappears from the screen.
Any solution?
You can use Vector2.Lerp() to move smoothly between two points.
Some pseudo code:
bool move;
float t;
Update()
{
if () // insert condition to begin movement
{
move = true;
t = 0; // reset timer
startPos = transform.position; // store current position for lerp
finalPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (move)
MovePlayer();
}
void MovePlayer()
{
t += Time.deltaTime / 3f; // 3 is seconds to take to move from start to end
transform.position = Vector2.Lerp(startPos, finalPosition, t);
if (t > 3)
{
move = false; // exit function
}
}
in update:
transform.position += (final_pos - transform.position).normalized * Time.deltaTime;
this is adding to your current position the direction ... use delta time to scale the movement and you can increase or decrease the speed by multiplying it all by some scalar value, ie any float value. note that it’s best to normalize once rather than every frame but this is the general idea.
I'm new to Unity and rigidbodies, and I thought I'd learn by trying to make a 3D Tron Light-cycle game. I've made my player vehicle using a combination of cylinders, spheres, and rectangles, seen below:
I used a rigid body on the elongated sphere, and used the following code:
public float accel = 1.0f;
// Use this for initialization
void Start () {
cycleSphere = GetComponent<Rigidbody>();
}
void FixedUpdate () {
cycleSphere.velocity = Vector3.forward * accel;
}
That moves the vehicle forwards. I'm not sure if there's a better way to do this, but if there is, please do say so.
I've attached the Main camera to the vehicle, and disabled X rotation to prevent it and the camera from rolling.
Now I would like to get it to turn by pressing the A and D buttons. Unlike the 90 degree turning of the original Tron light-cycles, I wanted it to turn like a regular vehicle.
So I tried this:
void Update () {
if (Input.GetKey (KeyCode.A)) {
turning = true;
turnAnglePerFixedUpdate -= turnRateAngle;
} else if (Input.GetKey (KeyCode.D)) {
turning = true;
turnAnglePerFixedUpdate += turnRateAngle;
} else {
turning = false;
}
}
void FixedUpdate () {
float mag = cycleSphere.velocity.magnitude;
if (!turning) {
Quaternion quat = Quaternion.AngleAxis (turnAnglePerFixedUpdate, transform.up);// * transform.rotation;
cycleSphere.MoveRotation (quat);
}
cycleSphere.velocity = Vector3.forward * accel;
}
While the above code does rotate the vehicle, it still moves in the last direction it was in - it behaves more like a tank turret. Worse, pressing either A or D too much would cause it to rotate in the desired direction and, after a short while, go nuts, rotating this way and that, taking the camera with it.
What did I do wrong and how can I fix it?
First of all I would recommend you to change from Input.GetKey to Input.GetAxis which will gracefully increase or decrease it's value when the key is pressed. This will give you the option to normalize the force vector applied as your velocity. Then based on that vector you have to adapt your force input so that the "front wheel" will "drag" the rest of the body to some other direction ( left or right ). This is not the ideal "real world physics behavior" because the forward force is slightly bigger than the side ( left or right ) force.
code example :
// member fields
float sideForceMultiplier = 1.0f;
float frontForceMultiplier = 2.0f;
Vector3 currentVeloticy = Vector3.zero;
void Update()
{
Vector3 sideForce = (sideForceMultiplier * Input.GetAxis("horizontal")) * Vector3.right;
Vector3 frontForce = frontForceMultiplier * Vector3.forward;
currentVelocity = (sideForce + fronForce).Normalize;
}
void FxedUpdate()
{
cycleSphere.velocity = currentVelocity * accel;
}
I have a ball which rotates around the point 0,0,0 in the Z-axis. When the space button is pressed, the ball has to go inside the large circle. Now my code looks like this. When you press space, the ball does not behave as they should. I want to know how to make a balloon down exactly down
that's how the ball should behave ->
behavior image
my code:
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) {
transform.position = new Vector3 (transform.position.x - 1, transform.position.y - 1, 0);
} else {
transform.RotateAround(new Vector3(0,0,0), new Vector3(0,0,1), 2);
}
}
Your code to 'jump' the orbit doesn't do what you want because Transform.RotateAround modifies both the rotation and the position of the object's transform.
So jumping to (position - 1,1,0) in the world is going to return wildly different results every time.
What you want to do instead is calculate the (Vector) direction from the object to the centre of orbit (the difference), then scale that down to how far you want it to move, then apply it to the position.
private Vector3 _orbitPos = Vector3.zero;
private float _orbitAngle = 2f;
private float _distanceToJump = 2f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
var difference = (_orbitPos - transform.position).normalized * _distanceToJump;
transform.Translate(difference);
}
transform.RotateAround(_orbitPos, Vector3.forward, _orbitAngle);
}
This will move the object to be orbiting 2 units closer when space is pressed immediately.
If you wanted to have a smooth transition instead of a jump, look into using Mathf.Lerp, Vector3.Lerp and the routines involved.