- Home /
Offset texture ONCE on key press
Hiya all! I've been searching for the answer to this for like an hour now so I figured I'd just ask myself haha
I'm trying to make a texture (512x256) that has 8 different faces on it offset. The model's head is UV'd to one facial expression and when you offset the texture/UVs by 0.25 on X the UVs perfectly fit the next expression (and 0.5 on Y).
I'm not exactly a programmer and the only script I can find that will offset just pans through it constantly. This is the code I've grabbed from http://docs.unity3d.com/ScriptReference/Material-mainTextureOffset.html:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float scrollSpeed = 0.5F;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
}
void Update() {
float offset = Time.time * scrollSpeed;
rend.material.mainTextureOffset = new Vector2(offset, 0);
}
}
I've seen that you could animate the UVs within Unity's animator but I'd prefer 2 float values (X and Y) that I could change within the inspector. It's probably super easy considering I just want values in the Material inspector to change. If we can just get it to go up on the X by 0.25 on [KeyPressA] and go up by 0.5 on the Y on [KeyPressB] I should be fine to adapt that to other inputs.
If anyone can direct me to what I need to remove from this code I will be super grateful!
Answer by zach-r-d · Jun 13, 2015 at 10:53 AM
You want to use the following Input.GetKeyDown in your Update() method, like this:
if (Input.GetKeyDown("Q")) {
rend.material.mainTextureOffset += new Vector2(/* x offset */);
}
if (Input.GetKeyDown("W")) {
rend.material.mainTextureOffset += new Vector2(/* y offset */);
}
Input.GetKeyDown only returns true when the key has gone from up to down on that frame (compared to Input.GetKey, which is true every frame until the key is up again).
Thanks for your response Zach!
So this is definitely the Update() method I needed just help me out one bit more and let me know what I'm whacking in the
+= new Vector2(/* x offset */);
part? It doesn't seem to like me using
+= new Vector2(0.25);
and that's obviously because we're not stating we want a new value in the X alone. Using
(0.25,0);
didn't work either... what am I doing wrong here hahaha
For the x offset, you would pass (.25f, 0f), and for y offset, you would pass (0f, .5f)
Oh my god you did it I love you man hahaha - thanks so much! Works like a charm ^^
Your answer
Follow this Question
Related Questions
Texture offset not behaving like it should (?) 1 Answer
Offset detail texture in c# 1 Answer
Scroll Ball Texture Smoothly 0 Answers
Why can't I animate texture offset? 1 Answer