Look at +1z of target and move to -1z of target? Almost there!

Hello guys, I am doing a small assignment for Uni where we have to make a small game.

I am doing a nokia style snake game in 3d where it follows gravity to platenauts (little planets)

At the moment I am in the script stage where I use simple shapes (spheres) to follow each other (and will grow and shorten depending on how much fruit it eats of if it hits walls)

After a whole day of looking around and testing its working well and I am happy! I still need to tweak it a little bit and I need to ask, how can I add +1 Z position to “look at” and -1 Z position to move at from target. If I can change this +1 or -1 numbers to look at and move at variables that would be more flexible. Anyone with good programming techniques should know this at a glace, but after one hour I cant find much.

This is the code I am using, they are following a empty game object that is positioned at -1 Z as a child of the spheres (the snake parts) but id like to eventually use a variable instead that indicates “target.position - (z.-1)” and look “target.position + (z.+1)”

This is the code I am using at the moment

var target : Transform;
var smooth = 5.0;
var damping = 6.0; 


function Update () {
    transform.position = Vector3.Lerp (
        transform.position, target.position,
        Time.deltaTime * smooth);
	
	var rotation = Quaternion.LookRotation((target.position + Vector3(0, 0, 1)) - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}

ps the position has to be local from the object it self

Thanks in advance!

2 Answers

2

Not sure I followed all that, but it sounds like you may need the transform.forward member.

You can use target.position + target.forward and target.position - target.forward to get the points 1 unit in front of and behind an object.

So I got the code working, but its not idea only because I am using multiples to use with target.forward instead of variables to change the vector3, and I also need to clap the rotations of every axis.

    var target : Transform;
var smooth = 5.0;
var damping = 6.0; 
var lookatDistanceZ: float = 2;
var moveatDistanceZ:float = 4;
var lookatDistance:Vector3 = Vector3(0,0,lookatDistanceZ);
var moveatDistance:Vector3 = Vector3(0,0,moveatDistanceZ);



function Update () {
    transform.position = Vector3.Lerp (
        transform.position, (target.position - (target.forward*moveatDistanceZ)),
        Time.deltaTime * smooth);
	
	var rotation = Quaternion.LookRotation((target.position + (target.forward*lookatDistanceZ)) - transform.position);
			transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}