I have a sprite that moves on the bottom of the screen from left to right if you press down left and right key.
I want to be able to shoot something (any sprite I want) from the sprite that is moving on the bottom of the screen and have that sprite just go directly up.
How could I do this?
Don't copy and paste this exactly but it's going to look something like this when you split those classes:
namespace SpaceInvadersGame
{
class Player : Microsoft.Xna.Framework.Game
{
Texture2D PlayerTexture;
Vector2 PlayerPosition;
public Player()
{
}
protected override void LoadContent()
{
PlayerTexture = Content.Load<Texture2D>(#"Images/freshman2");;
PlayerPosition = Vector2.Zero;
base.LoadContent();
}
public Vector2 GetPosition()
{
return this.PlayerPosition;
}
public void Update()
{
KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Left))
freshamPos.X -= freshmanSpeed;
if (keyboardState.IsKeyDown(Keys.Right))
freshamPos.X += freshmanSpeed;
if(keyboardState.IsKeyDown(Keys.Space))
theBullet = new Bullet(this);
}
public void Draw(SpriteBatch SpriteBatch)
{
}
}
}
namespace SpaceInvadersGame
{
class Bullet : Microsoft.Xna.Framework.Game
{
Texture2D BulletTexture;
Vector2 BulletPosition;
Player thePlayer;
public Bullet(Player player)
{
this.thePlayer = player;
}
protected override void LoadContent()
{
BulletTexture = Content.Load<Texture2D>(#"Images/bullet");;
BulletPosition = thePlayer.GetPosition();
base.LoadContent();
}
public void Update()
{
//in here is where you would just do something like:
//BulletPosition.Y += 1;
}
public void Draw(SpriteBatch SpriteBatch)
{
}
}
}
Related
this is my first post here. I'm doing pong game in Unity, and i have problem finding instantinated gameobject ball, which i want to gets it's position to program AI controlling second Paddle. Here how it looks like:
GameController.cs:
public class GameController : MonoBehaviour
{
public GameObject ballPrefab;
public Text score1Text;
public Text score2Text;
public float scoreCoordinates = 3.4f;
private Ball2 currentBall;
private int score1 = 0;
private int score2 = 0;
// Start is called before the first frame update
void Start()
{
SpawnBall();
}
void SpawnBall()
{
GameObject ballInstance = Instantiate(ballPrefab, transform);
currentBall = ballInstance.GetComponent<Ball2>();
currentBall.transform.position = Vector3.zero;
score1Text.text = score1.ToString();
score2Text.text = score2.ToString();
}
// Update is called once per frame
void Update()
{
if (currentBall != null)
{
if (currentBall.transform.position.x > scoreCoordinates)
{
score1++;
Destroy(currentBall.gameObject);
SpawnBall();
}
if (currentBall.transform.position.x < -scoreCoordinates)
{
score2++;
Destroy(currentBall.gameObject);
SpawnBall();
}
}
}
}
AI.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI : MonoBehaviour
{
private Rigidbody2D AIrig;
private Ball2 ball;
public float speed = 1f;
// Start is called before the first frame update
void Start()
{
ball = GetComponent<Ball2>();
AIrig = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
ball.transform.position = Vector3.zero;
if (ball.transform.position.y > AIrig.transform.position.y)
{
AIrig.velocity = new Vector2(0, speed);
}
else if (ball.transform.position.y > AIrig.transform.position.y)
{
AIrig.velocity = new Vector2(0, -speed);
}
}
}
Ball2.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball2 : MonoBehaviour
{
public float minXspeed = 0.8f;
public float maxXspeed = 1.2f;
public float minYspeed = 0.8f;
public float maxYspeed = 1.2f;
private Rigidbody2D ballRigidbody;
// Start is called before the first frame update
void Start()
{
ballRigidbody = GetComponent<Rigidbody2D>();
ballRigidbody.velocity = new Vector2(Random.Range(minXspeed, maxXspeed) * (Random.value > 0.5f ? -1 : 1), Random.Range(minYspeed, maxYspeed) * (Random.value > 0.5f ? -1 : 1));
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D otherCollider)
{
if (otherCollider.tag == "Limit")
{
if (otherCollider.transform.position.y > transform.position.y && ballRigidbody.velocity.y > 0)
{
ballRigidbody.velocity = new Vector2(ballRigidbody.velocity.x, -ballRigidbody.velocity.y);
}
if (otherCollider.transform.position.y < transform.position.y && ballRigidbody.velocity.y < 0)
{
ballRigidbody.velocity = new Vector2(ballRigidbody.velocity.x, -ballRigidbody.velocity.y);
}
}
else if (otherCollider.tag == "Paddle")
{
if (otherCollider.transform.position.x < transform.position.x && ballRigidbody.velocity.x < 0)
{
ballRigidbody.velocity = new Vector2(-ballRigidbody.velocity.x, ballRigidbody.velocity.y);
}
if (otherCollider.transform.position.x > transform.position.x && ballRigidbody.velocity.x > 0)
{
ballRigidbody.velocity = new Vector2(-ballRigidbody.velocity.x, ballRigidbody.velocity.y);
}
}
}
}
I can't get refference to instantinated object (ball). If anyone could help me i will be grateful.
All right, i get it, here is the solution:
I've modified AI.cs, now it looks like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI : MonoBehaviour
{
private Rigidbody2D AIrig;
public GameObject ball;
public float speed = 1f;
// Start is called before the first frame update
void Start()
{
AIrig = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
ball = GameObject.Find("Ball(Clone)");
if (ball.transform.position.y > AIrig.transform.position.y)
{
AIrig.velocity = new Vector2(0, speed);
}
else if (ball.transform.position.y < AIrig.transform.position.y)
{
AIrig.velocity = new Vector2(0, -speed);
}
}
}
I am not exactly clear where are those scripts attached.
So, I don't know if your getComponent will work.
GetComponent will work if you have scripts attached to the same object
Otherwise, you have can consider options like FindObjectOfType(), FindGameObjectsWithTag(string tag), GameObject.Find("object name") and more...
But I think the best way to do it, is if you want one object reference then store the instantiated ball to a public variable, and access it through it.
And if you are instantiating multiple objects, then store them in the public list in GameController. Then in the start function take the reference of the game controller and you will have access to those public variables.
In XNA, i want to manage background sound for every game state. For example; StartMenu music will be playing when option is Start or Playing music will be playing when option is Playing. I arranged code as followed, as you can see i create play and stop method inside all sound class but it's only working while exiting to game.
public abstract class Sound
{
public SoundEffect Item { get; set; }
public Song BgSound { get; set; }
public abstract void LoadContent(ContentManager content);
public abstract void Play();
public abstract void Stop();
}
public class GameSound : Sound
{
public GameSound()
{
BgSound = null;
Item = null;
}
public override void LoadContent(ContentManager content)
{
BgSound = content.Load<Song>("Sounds/BgSound");
MediaPlayer.IsRepeating = true;
}
public override void Play()
{
MediaPlayer.Play(BgSound);
}
public override void Stop()
{
MediaPlayer.Stop();
}
}
public class StartUpSound : Sound
{
public StartUpSound()
{
BgSound = null;
Item = null;
}
public override void LoadContent(ContentManager content)
{
BgSound = content.Load<Song>("Sounds/StartUp");
MediaPlayer.IsRepeating = false;
}
public override void Play()
{
MediaPlayer.Play(BgSound);
}
public override void Stop()
{
MediaPlayer.Stop();
}
}
public class GameBase : Microsoft.Xna.Framework.Game
{
//..
GameSound gameSoundFx = new GameSound();
StartUpSound startUpSoundFx = new StartUpSound();
//..
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
gameSoundFx.LoadContent(Content);
startUpSoundFx.LoadContent(Content);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
if (currentState == GameState.StartMenu)
{
startUpSoundFx.Play();
}
if (currentState == GameState.Playing)
{
startUpSoundFx.Stop();
gameSoundFx.Play();
}
spriteBatch.End();
base.Draw(gameTime);
}
}
Edited
Also i tried again like this but nothing has changed;
if (currentState == GameState.StartMenu)
{
startUpSoundFx.BgSound = Content.Load<Song>("Sounds/StartUp");
MediaPlayer.Play(startUpSoundFx.BgSound);
}
if (currentState == GameState.Playing)
{
MediaPlayer.Stop();
gameSoundFx.BgSound = Content.Load<Song>("Sounds/StartUp");
MediaPlayer.Play(gameSoundFx.BgSound);
}
This has already been answered -
https://gamedev.stackexchange.com/questions/86038/c-how-to-properly-play-background-songs-in-xna
Please review the answer there, here's the example included -
switch (currentGameState)
{
case GameState.MainMenu:
if (musicState == MusicState.Playing && currentGameState != lastGameState)
{
MediaPlayer.Stop();
musicState = MusicState.NotPlaying;
}
if (musicState == MusicState.NotPlaying)
{
MediaPlayer.Play(song_mainTheme);
musicState = MusicState.Playing;
}
break;
case GameState.GamePlaying:
if (musicState == MusicState.Playing && currentGameState != lastGameState)
{
MediaPlayer.Stop();
musicState = MusicState.NotPlaying;
}
if (musicState == MusicState.NotPlaying)
{
MediaPlayer.Play(song_actionTheme);
musicState = MusicState.Playing;
}
break;
}
It shows extending the states to allow for proper use of the Mediaplayer - as stated in the comments of your question.
Hi I am trying to upgrade our ios app from mvvmcross v1 to v3. I can't figure out how to make my custom buttonrow work.
My view ViewDidLoad it is the button items that binds to the button row
public override void ViewDidLoad()
{
base.ViewDidLoad();
SortingView.ViewModel = ViewModel;
_shown = false;
// Setup View Animatons
Buttons.OnClick = () => { AnimationTransition = ViewTransitionAnimation.TransitionFade; };
TopRightButton.TouchDown +=
(sender, args) => {
AnimationTransition = ViewTransitionAnimation.TransitionCrossDissolve;
};
// Setup Bindings
this.AddBindings(
new Dictionary<object, string>
{
{this.BackgroundImage, "{'ImageData':{'Path':'BackgroundImage','Converter':'ImageItem'}}"},
{this.TopbarBackground, "{'ImageData':{'Path':'TopBarImage','Converter':'ImageItem'}}"},
{this.TopLogo, "{'ImageData':{'Path':'Logo','Converter':'ImageItem'}}"},
{this.Buttons, "{'ItemsSource':{'Path':'ButtonItems'}}"},
{this.SlideMenu, "{'ItemsSource':{'Path':'VisibleViews'}}"},
{
this.SortingView,
"{'ItemsSource':{'Path':'CategoriesName'},'SelectedGroups':{'Path':'SelectedGroups'},'ForceUbracoUpdateAction':{'Path':'ForceUbracoUpdateAction'}}"
},
{this.SettingsButton, "{'TouchDown':{'Path':'TopRightButtonClick'},'Hide':{'Path':'HideTopbarButton'},'ImageData':{'Path':'TopButtonImage','Converter':'ImageItem'}}" },
{this.TopRightButton, "{'TouchDown':{'Path':'SecondaryButtonButtonPushed'},'Hide':{'Path':'HideTopbarButton2'},'ImageData':{'Path':'SettingsButtonImage','Converter':'ImageItem'}}" }
});
// Perform any additional setup after loading the view, typically from a nib.
NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.DidBecomeActiveNotification, ReEnableSlideMenu);
this.SortingView.Hidden=true;
ViewModel.SettingButtonEvent += HandleSettingButtonPushed;
}
Here is my custom control "ButtonRow
[Register("ButtonRow")]
public class ButtonRow : CustomListViewController
{
private int _width = 0;
private UIImage _backgroundImage = null;
public ButtonRow(IntPtr handle)
: base(handle)
{
_width = (int)this.Frame.Width;
UseImageAsIcon = false;
FontSize=0;
}
public bool UseImageAsIcon { get; set; }
public UIImage BackgroundImage
{
get { return _backgroundImage; }
set { _backgroundImage = value; }
}
public int FontSize
{
get;set;
}
private Action _onClickAction;
private int _spacing = 0;
public Action OnClick
{
get
{
return _onClickAction;
}
set
{
_onClickAction = value;
}
}
/// <summary>
/// The add views.
/// </summary>
/// custom implementation for adding views to the button row
protected override void AddViews()
{
if (ItemsSource == null)
{
Hidden = true;
return;
}
base.AddViews();
foreach (UIView uiView in Subviews)
{
uiView.RemoveFromSuperview();
}
if (ItemsSource.Count == 0)
{
Hidden = true;
return;
}
if (_backgroundImage != null)
{
var frame = new RectangleF(0, 0, Frame.Width, Frame.Height);
var background = new UIImageView(frame) { Image = _backgroundImage };
AddSubview(background);
}
_width = _width - ((ItemsSource.Count - 1) * Spacing);
var buttonWidth = (int)Math.Ceiling (((double)_width) / ItemsSource.Count);
int index = 0;
foreach (ViewItemModel item in ItemsSource)
{
// creating custom button with needed viewmodel, nib etc is loaded in the class constructor
var button = new ButtonWithLabel(item, OnClick);
if (FontSize > 0)
{
button.FontSize(FontSize);
}
if (UseImageAsIcon)
{
button.AddBindings(
new Dictionary<object, string>
{
{ button, "{'IconLabel':{'Path':'Title'},'TitleFontColor':{'Path':'TitleFontColor'}}" },
{ button.icon, "{'ImageData':{'Path':'ImageIcon','Converter':'ImageItem'}}" }
});
}
else
{
// bindings created between the button and its viewmodel
button.AddBindings(
new Dictionary<object, string>
{
{button, "{'Label':{'Path':'Title'},'TitleFontColor':{'Path':'TitleFontColor'},'BackgroundColor':{'Path':'BackgroundColor'}}" },
{button.Background, "{'ImageData':{'Path':'ImageIcon','Converter':'ImageItem'}}" }
});
button.icon.Hidden = true;
}
// new frame of button is set, as the number of buttons is dynamic
int x = index == 0 ? 0 : index * (buttonWidth + Spacing);
button.SetFrame(new RectangleF(x, 0, buttonWidth, Frame.Height));
// the view of the button is added to the buttonrow view
AddSubview(button.View);
index++;
}
}
public int Spacing
{
get
{
return this._spacing;
}
set
{
this._spacing = value;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
public override void Cleanup()
{
if(Subviews!=null)
{
foreach (var view in Subviews)
{
view.RemoveFromSuperview();
}
}
if(_backgroundImage!=null)
{
_backgroundImage.Dispose();
}
ItemsSource = null;
}
}
Here is my CustomListViewController
public class CustomListViewController: UIView
{
private IList _itemsSource;
private CustomViewSource _viewSource;
public CustomListViewController(MvxShowViewModelRequest showRequest)
{
ShowRequest = showRequest;
}
protected CustomListViewController()
{
}
public CustomListViewController(IntPtr handle)
: base(handle)
{
}
public bool IsVisible
{
get
{
return this.IsVisible;
}
}
public IList ItemsSource
{
get { return _itemsSource; }
set { _itemsSource = value; if(value!=null){CreateViewSource(_itemsSource); }}
}
public virtual void CreateViewSource(IList items)
{
if (_viewSource == null)
{
_viewSource = new CustomViewSource();
_viewSource.OnNewViewsReady += FillViews;
}
_viewSource.ItemsSource = items;
}
private void FillViews(object sender, EventArgs e)
{
AddViews();
}
protected virtual void AddViews()
{
// get views from source and do custom allignment
}
public virtual void Cleanup()
{
if(_viewSource!=null)
{
_itemsSource.Clear();
_itemsSource=null;
_viewSource.OnNewViewsReady -= FillViews;
_viewSource.ItemsSource.Clear();
_viewSource.ItemsSource = null;
_viewSource=null;
}
}
public MvxShowViewModelRequest ShowRequest { get;
private set;
}
}
And My CustomViewSource
public class CustomViewSource
{
private IList _itemsSource;
private List<UIView> _views=new List<UIView>();
public event EventHandler<EventArgs> OnNewViewsReady;
public CustomViewSource ()
{
}
public List<UIView> Views { get { return _views; } }
public virtual IList ItemsSource
{
get { return _itemsSource; }
set
{
// if (_itemsSource == value)
// return;
var collectionChanged = _itemsSource as INotifyCollectionChanged;
if (collectionChanged != null)
collectionChanged.CollectionChanged -= CollectionChangedOnCollectionChanged;
_itemsSource = value;
collectionChanged = _itemsSource as INotifyCollectionChanged;
if (collectionChanged != null)
collectionChanged.CollectionChanged += CollectionChangedOnCollectionChanged;
ReloadViewData();
}
}
protected object GetItemAt(int position)
{
if (ItemsSource == null)
return null;
return ItemsSource[position];
}
protected void CollectionChangedOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
ReloadViewData();
}
protected virtual void ReloadViewData()
{
if(ItemsSource==null){return;}
foreach (var VARIABLE in ItemsSource)
{
//call create view and add it to Views
}
//event new views created
if(OnNewViewsReady!=null)
OnNewViewsReady(this,new EventArgs());
}
protected virtual UIView CreateUIView(int position)
{
UIView view = null;
/*
//create view from nib
UIView newView=null;
return newView;
* */
return view;
}
}
Any one have any clues on how to make this work in mvvmcross v3 ?
I would like to make it so i can add x number of buttons and load the buttons from nib files. Have looked at the Kittens collection view example, but have not figured out how to make it work for my buttonRow, not sure if the collectionView is the right one to use as base.
The most common way to show a list is to use a UITableView.
There are quite a few samples around that show how to load these in MvvmCross:
n=2 and n=2.5 in http://mvvmcross.wordpress.com/
n=6 and n=6.5 in http://mvvmcross.wordpress.com/
Working with Collections in https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/Working%20With%20Collections
In your case, it looks like the previous coder has implemented some sort of custom control with custom layout. Adapting this to v3 shouldn't be particularly difficult, but you are going to need to read through and understand the previous code and how it works (this is nothing to do with MvvmCross - it's just app UI code).
One sample on dealing with custom views like this in iOS is the N=32 tutorial - http://slodge.blogspot.co.uk/2013/06/n32-truth-about-viewmodels-starring.html
Hi friends basically i am a android developer. i am newbie in blackberry development. i need to create the custom text box with image button.
in the right corner of the text box, i want the small image button and it's click listener the text box field should be empty.
i Can create the Custom Text box and also draw bitmap inside the text box. but i can't catch the focus and listener to the image button. please help me
Please give some idea and samples.
I tried this...
MyApp.java Class:
import net.rim.device.api.ui.UiApplication;
public class MyApp extends UiApplication {
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new MyScreen());
}
}
MyScreen.java class:
public final class MyScreen extends MainScreen {
public MyScreen() {
super(Manager.NO_VERTICAL_SCROLL);
setTitle("MyTitle");
VerticalFieldManager vfm = new VerticalFieldManager(
Manager.USE_ALL_HEIGHT | Manager.USE_ALL_HEIGHT);
HorizontalFieldManager hfm = new HorizontalFieldManager(
Manager.USE_ALL_WIDTH);
HorizontalFieldManager hfm1 = new HorizontalFieldManager(
Manager.USE_ALL_WIDTH);
customManager ctm = new customManager(Manager.USE_ALL_WIDTH);
customManager ctm1 = new customManager(Manager.USE_ALL_WIDTH);
hfm.add(ctm);
hfm1.add(ctm1);
vfm.add(hfm);
vfm.add(hfm1);
add(vfm);
}
}
customManager.java Class:
public class customManager extends Manager implements FieldChangeListener {
private Textbox txt;
private Closebtn cls;
Bitmap bitmap;
protected customManager(long style) {
super(style);
// My Coustem TextBOX
txt = new Textbox(300, 100);
// My Coustem Button
cls = new Closebtn();
cls.setChangeListener(this);
add(txt);
add(cls);
}
protected void sublayout(int width, int height) {
setPositionChild(getField(0), 10, 10);
layoutChild(getField(0), getField(0).getPreferredWidth(), getField(0)
.getPreferredHeight());
setPositionChild(getField(1),
getField(0).getWidth() - (getField(1).getWidth()), getField(0)
.getHeight() / 2 - getField(1).getHeight() / 2);
layoutChild(getField(1), getField(1).getWidth(), getField(1)
.getHeight());
setExtent(width, height);
}
public void fieldChanged(Field field, int context) {
txt.setText("");
}
}
Textbox.java Class:
public class Textbox extends Manager {
private int managerWidth;
private int managerHeight;
private int arcWidth;
private VerticalFieldManager vfm = new VerticalFieldManager(
NO_VERTICAL_SCROLL | USE_ALL_WIDTH );
private EditField editField;
private Bitmap bagBitmap;
Textbox(int width, int height, long style) {
super(style | NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL);
managerWidth = width;
managerHeight = height;
long innerStyle = style & (READONLY | FOCUSABLE_MASK); // at least
if (innerStyle == 0) {
innerStyle = FOCUSABLE;
}
editField = new EditField("", "", 10, innerStyle);
arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE; // make it even
EncodedImage en = EncodedImage.getEncodedImageResource("_text.png");
bagBitmap = Util.getScaledBitmapImage(en, width, height);
add(vfm);
vfm.add(editField);
}
public void setFont(Font font) {
super.setFont(font);
editField.setFont(font);
arcWidth = editField.getFont().getHeight() & 0xFFFFFFFE;
updateLayout();
}
Textbox(int width, int height) {
this(width, height, 0L);
}
public String getText() {
return editField.getText();
}
public void setText(String newText) {
editField.setText(newText);
}
public int getPreferredWidth() {
return managerWidth;
}
public int getPreferredHeight() {
return managerHeight;
}
protected void sublayout(int w, int h) {
if (managerWidth == 0) {
managerWidth = w;
}
if (managerHeight == 0) {
managerHeight = h;
}
int actWidth = Math.min(managerWidth, w);
int actHeight = Math.min(managerHeight, h);
layoutChild(vfm, actWidth - arcWidth, actHeight - arcWidth);
setPositionChild(vfm, arcWidth / 2, arcWidth / 2);
setExtent(actWidth, actHeight);
}
protected void paint(Graphics g) {
g.drawBitmap(0, 0, getWidth(), getHeight(), bagBitmap, 0, 0);
super.paint(g);
}
}
Closebtn.java Class:
public class Closebtn extends Field {
private Bitmap bitmap;
public Closebtn() {
super(Manager.FOCUSABLE);
EncodedImage en = EncodedImage.getEncodedImageResource("close.png");
bitmap = Util.getScaledBitmapImage(en, 50, 50);
}
protected void layout(int width, int height) {
setExtent(bitmap.getWidth(), bitmap.getHeight());
}
protected void paint(Graphics graphics) {
graphics.drawBitmap(0, 0, bitmap.getWidth(), bitmap.getHeight(),
bitmap, 0, 0);
}
protected void onFocus(int direction) {
bitmap = bitmap;
}
protected void onUnfocus() {
bitmap = bitmap;
}
protected boolean keyChar(char character, int status, int time) {
if (character == Characters.ENTER) {
clickButton();
return true;
}
return super.keyChar(character, status, time);
}
protected boolean navigationClick(int status, int time) {
clickButton();
return true;
}
protected boolean trackwheelClick(int status, int time) {
clickButton();
return true;
}
protected boolean invokeAction(int action) {
switch (action) {
case ACTION_INVOKE: {
clickButton();
return true;
}
}
return super.invokeAction(action);
}
public void setDirty(boolean dirty) {
}
public void setMuddy(boolean muddy) {
}
public void clickButton() {
fieldChangeNotify(0);
}
}
Util.java Class:
public class Util {
public static Bitmap getScaledBitmapImage(EncodedImage image, int width,
int height) {
if (image == null) {
return null;
}
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
requiredHeightFixed32);
image = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return image.getBitmap();
}
}
My problem is i can't add more then one fields here Pls help me..
Try this custom class:
public class TextFieldWithClear extends HorizontalFieldManager {
protected HorizontalFieldManager hfmEditTextPanel;
protected LabelField lblEditText;
protected EditField textField;
protected MyImageButton bitmapFieldClear;
int mHeight;
int mWidth;
String mLabel;
public TextFieldWithClear(String label, int width, int height) {
super(FOCUSABLE);
Border border = BorderFactory
.createSimpleBorder(new XYEdges(2, 2, 2, 2));
this.setBorder(border);
Background bg = BackgroundFactory.createSolidBackground(Color.WHITE);
this.setBackground(bg);
mWidth = width;
mHeight = height;
mLabel = label;
lblEditText = new LabelField(mLabel) {
protected void paint(Graphics graphics) {
graphics.setColor(0x4B4B4B);
super.paint(graphics);
}
};
add(lblEditText);
hfmEditTextPanel = new HorizontalFieldManager(FOCUSABLE
| VERTICAL_SCROLL | VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
maxWidth = mWidth - 30;
maxHeight = mHeight;
super.sublayout(maxWidth, maxHeight);
setExtent(maxWidth, maxHeight);
}
};
textField = new EditField() {
// protected void layout(int width, int height)
// {
// width = mWidth - 50;
// height=35;
// super.layout(width, height);
// //setExtent(width, height);
// }
};
hfmEditTextPanel.add(textField);
add(hfmEditTextPanel);
bitmapFieldClear = new MyImageButton(
Bitmap.getBitmapResource("btn_delete_normal.png"),
Bitmap.getBitmapResource("btn_delete_focused.png"));
bitmapFieldClear.setChangeListener(buttonListener);
add(bitmapFieldClear);
}
public String getText() {
String value = "";
if (textField.getText().length() > 0)
value = textField.getText();
return value;
}
public void setString(String value) {
if (value != null) {
textField.setText(value);
}
}
FieldChangeListener buttonListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
textField.clear(0);
textField.setFocus();
}
};
public void onUndisplay()
{
textField.setEditable(false);
}
public void onDisplay()
{
textField.setEditable(true);
}
}
This is not easy to do just overriding EditField, so this is what I'd try:
Use an horizontal manager (for instance, HorizontalFieldManager or other custom manager, perhaps with fixed column widths. This manager would have two fields inside: at left an EditField, at right a custom buttonfield.
Set a Background to the manager. The bg would draw the green background as well as the blue border. You can use an scaled bitmap (have a look at BackgroundFactory.createBitmapBackground).
Create a new EditField subclass, and override its paintBackground method so that it does nothing. If it does not work, try overriding paint so that it does only draw the text. This is the trickiest part.
Create a custom Buttonfield subclass with the cross over gray circle image. You can read a good tutorial on how to do that here. You also have available an already made BitmapButtonField in the Advanced Ui Library. When the button is clicked, it would invoke EditField.setText("") on the EditField.
I get the error as said above, which prevents me from testing to see whether my camera is working. The code is:
protected override void Update(GameTime gameTime)
{
KeyboardState keyBoardState = Keyboard.GetState();
//Rotate Cube along its Up Vector
if (keyBoardState.IsKeyDown(Keys.X))
{
cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, .02f) * cubeWorld;
}
if (keyBoardState.IsKeyDown(Keys.Z))
{
cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, -.02f) * cubeWorld;
}
//Move Cube Forward, Back, Left, and Right
if (keyBoardState.IsKeyDown(Keys.Up))
{
cubeWorld *= Matrix.CreateTranslation(cubeWorld.Forward);
}
if (keyBoardState.IsKeyDown(Keys.Down))
{
cubeWorld *= Matrix.CreateTranslation(cubeWorld.Backward);
}
if (keyBoardState.IsKeyDown(Keys.Left))
{
cubeWorld *= Matrix.CreateTranslation(-cubeWorld.Right);
}
if (keyBoardState.IsKeyDown(Keys.Right))
{
cubeWorld *= Matrix.CreateTranslation(cubeWorld.Right);
}
}
The line causing an error is:
protected override void Update(GameTime gameTime)
You are not inheriting from GameComponent, you have two options:
Inherite your class from GameComponent:
public class YourCameraClass : GameComponent { .... }
Remove the 'override' keyword in your update method declaration:
public void Update(Gametime gametime) {....}