- Home /
The question is answered, right answer was accepted
How to smooth out movement in a 3D space?
Hello Unity Community!
I am currently working on a 3D space combat game (chicken invaders styled). I've been working on my ship controller, using code like transform.Translate(-Time.deltaTime*speed,0,0);
to move my object.
However, it seemed very jerky, so I tried using Vector3.SmoothDamp() instead. Here's how the code looks
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class ShipController : MonoBehaviour {
public int speed = 20;
public float smoothTime ;
private Vector3 velocity = Vector3.zero;
Vector3 targetPosition;
private void Start()
{
smoothTime = (100/speed);
targetPosition = new Vector3(-1000,0,0);
}
void Update() {
//CLAMPING
Vector3 pos = Camera.main.WorldToViewportPoint (transform.position);
pos.x = Mathf.Clamp(pos.x, 0.09f, 0.91f);
pos.y = Mathf.Clamp(pos.y, 0.15f, 0.9f);
transform.position = Camera.main.ViewportToWorldPoint(pos);
if(Input.GetKey(KeyCode.A))
{
transform.position = Vector3.SmoothDamp(this.transform.position, targetPosition, ref velocity, smoothTime);
}
}
}
It works well, smooth, responsive and flexible. It has only one problem: since I'm using targetPosition = new Vector3(-1000,0,0);
, my object translates to the left, but also towards the center. I want my object to move only to the left, and not hover towards the center, regardless of its current position.
Or, if someone could suggest and exemplify a different method of implementing this movement, it would be most welcomed.
Thank you for your time!
Answer by NoseKills · Oct 03, 2014 at 11:39 AM
Your targetPosition has a y-coordinate of 0. I assume that (0,0,0) is in the center of the screen.
Try something like this.
private void Start()
{
smoothTime = (100/speed);
targetPosition = this.transform.position;
targetPosition.x = -1000;
}
This way you set the y and z coordinates to their old values and only change the x.
I thought it would be something like this, thank you. Works great!
Follow this Question
Related Questions
Limit & Scaling Translation Rate. 0 Answers
stop object(door) translation 0 Answers
a better movement code C# 3 Answers
C# Smoothing Out transform.Translate 4 Answers
Help with casting a raycast C# 1 Answer